我的所有指令都使用相同的作用域,并且我希望我的指令能够自行运行。
指令:
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”并按年龄排序。我当然希望每一列都对其自己的列进行排序。我怎样才能实现这个目标?
更新:
忘了提及 orderField
和 reverse
用于 ng-repeat | 中。订单依据
:
<tbody id="customerRows" data-ng-repeat="customer in customers | orderBy:orderField:reverse">
最佳答案
指令的每个实例都需要有自己的标题、排序类型和反向属性。因此,该指令需要自己的(子)作用域 - 一个隔离作用域 (scope: {}
) 或一个新作用域 (scope: 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 在 fiddle 中,为了简单起见,我没有包含 FullName 列。
关于angularjs - 如何防止 Angular 指令之间共享作用域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16858862/