如何防止 Angular 指令之间共享作用域?

2023-11-21

我的所有指令都使用相同的范围,并且我希望我的指令能够自行运行。

指示:

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>

结果是所有列的值为“年龄”并按年龄排序。我当然希望每一列都对其自己的列进行排序。我怎样才能实现这个目标?

更新: 忘记说了orderField and reverse用于ng-repeat | orderBy:

<tbody id="customerRows" data-ng-repeat="customer in customers | orderBy:orderField:reverse">

指令的每个实例都需要有自己的标题、排序类型和反向属性。因此该指令需要它自己的(子)作用域——或者是一个隔离作用域(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.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何防止 Angular 指令之间共享作用域? 的相关文章

随机推荐