我的所有指令都使用相同的范围,我希望我的指令可以自己操作.
指示:
app.directive('headerSort',function () { return { restrict: 'A',controller: function ($scope,$element,$attrs) { $scope.caption = $attrs.caption; $scope.doSort = function () { $scope.orderField = $attrs.headerSort; $scope.reverse = !$scope.reverse; }; },template: '<div data-ng-click="doSort();">' + '{{caption}}' + '<i class="icon-sort"></i>' + '</div>' }; });
HTML:
<th data-header-Sort="FullName" data-caption="Full name"></th> <th data-header-Sort="FirsName" data-caption="First name"></th> <th data-header-Sort="Age" data-caption="Age"></th>
结果是所有列都具有值’Age’并按Age排序.我当然希望每列都对它自己的列进行排序.我怎样才能做到这一点?
更新:
忘了在ng-repeat中使用orderField和reverse排序依据:
<tbody id="customerRows" data-ng-repeat="customer in customers | orderBy:orderField:reverse">
指令的每个实例都需要有自己的标题,排序类型和反向属性.因此该指令将需要其自己的(子)范围 – 隔离范围(范围:{})或新范围(范围:true).由于该指令不是独立/自包含组件,因此我不会使用隔离范围(另请参阅
When writing a directive in AngularJS,how do I decide if I need no new scope,a new child scope,or a new isolated scope?).
使用为指令选择的作用域类型,可以通过函数参数将排序类型和反向值传递给父类,也可以直接在父作用域上设置它们.我建议函数参数:
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在小提琴中,为简单起见,我没有包含FullName列.