指令的每个实例都需要有自己的标题、排序类型和反向属性。因此该指令需要它自己的(子)作用域——或者是一个隔离作用域(scope: {}
)或新范围(scope: true
)。由于该指令不是独立/独立的组件,因此我不会使用隔离范围(另请参阅在 AngularJS 中编写指令时,如何决定是否需要新的作用域、新的子作用域或新的隔离作用域?).
根据为指令选择的作用域类型,排序类型和反向值可以通过函数参数传递给父级,也可以直接在父级作用域上设置。我建议函数参数:
app.directive('headerSort', function () {
return {
scope: true, // creates a new child scope
link: function (scope, element, attrs) {
scope.caption = attrs.caption;
scope.sortType = attrs.headerSort;
scope.reverse = false;
},
template: '<div data-ng-click="reverse=!reverse; doSort(sortType, reverse);">' +
'{{caption}}</div>'
};
});
function MyCtrl($scope) {
$scope.orderField = "FirstName";
$scope.reverse = false;
$scope.customers = [ {FirstName: 'Martijn', Age: 22}, {FirstName: 'Mark', Age: 44}];
$scope.doSort = function (sortType, reverse) {
console.log('sorting',sortType, reverse);
$scope.orderField = sortType;
$scope.reverse = reverse;
};
}
<table>
<th data-header-sort="FirstName" data-caption="First name"></th>
<th data-header-sort="Age" data-caption="Age"></th>
<tbody id="customerRows" data-ng-repeat="customer in customers | orderBy:orderField:reverse">
<tr><td>{{customer.FirstName}}<td>{{customer.Age}}
</tbody>
</table>
fiddle In the fiddle, just for simplicity, I did not include the FullName column.