我使用AngularJS的智能表插件设置了一个表。一切看起来都很好用。我不想让用户点击表头来触发排序,而是想以编程方式从我的Angular控制器中触发排序。我在这里的文档中没有看到这样做的方法:
http://lorenzofox3.github.io/smart-table-website/
我忽略了什么吗?
这是执行此操作的“有角度”方式。写一个指令。该指令可以访问智能表控制器。它将能够按功能调用控制器的排序。我们将命名新指令stSortBy。
下面的HTML包括标准的智能表合成糖。这里唯一的新属性指令是st-sort-by。这就是魔术将要发生的地方。它绑定到范围变量sortByColumn。这是要排序的列的字符串值
<table st-sort-by="{{sortByColumn"}}" st-table="displayedCollection" st-safe-src="rowCollection">
<thead>
<tr>
<th st-sort="column1">Person</th>
<th st-sort="column2">Person</th>
</tr>
</thead>
</table>
<button ng-click="toggleSort()">Toggle sort columns!</button>
这是挂钩到st表控制器的stSortBy指令
app.directive('stSortBy', function() {
return {
require: 'stTable',
link: function (scope, element, attr, ctrl) {
attr.$observe('stSortBy', function (newValue) {
if(newValue) {
// ctrl is the smart table controller
// the second parameter is for the sort order
ctrl.sortBy(newValue, true);
}
});
}
};
});
这是控制器。控制器在其范围内设置排序
app.controller("MyTableWrapperCtrl", ["$scope", function($scope) {
$scope.sortByColumn = 'column2';
$scope.toggleSort = function() {
$scope.sortByColumn = $scope.sortByColumn === 'column2' ? 'column1' : 'column2';
// The time out is here to guarantee the attribute selector in the directive
// fires. This is useful is you do a programmatic sort and then the user sorts
// and you want to programmatically sort back to the same column. This forces a sort, even if you are sorting the same column twice.
$timeout(function(){
$scope.sortByColumn = undefined;
}, 0);
};
}]);