使用 AngularJS 从指令设置范围变量

Setting a scope variable from a directive with AngularJS

本文关键字:范围 变量 设置 指令 AngularJS 使用      更新时间:2024-02-02

我已经在SO上提出了20个类似的问题,但还没有找到适合我的情况的解决方案,所以我希望你们能帮助我。

目标是按指令的"sort-type"属性中提供的属性对名称列表进行排序,但仅适用于每个控制器中的列表(而不是同时对所有列表(。

.HTML

<div ng-controller="TestController as testOne">
   <b>By:</b> {{testOne.sortType}}<br>
   <b>Reverse:</b> {{testOne.sortReverse}}<br>
   <div ng-repeat="item in testOne.list">
       <p table-sort sort-type="name" sort-reverse="false"><a href="#">Sort by name</a></p>
       <ul>
           <li ng-repeat="childItem in testOne.childList | orderBy:testOne.sortType">{{childItem.name}}</li>
       </ul>
   </div>
</div>
<br><br>
<div ng-controller="TestController as testTwo">
   <b>By:</b> {{testTwo.sortType}}<br>
   <b>Reverse:</b> {{testTwo.sortReverse}}<br>
   <div ng-repeat="item in testTwo.list">
       <p table-sort sort-type="name" sort-reverse="false"><a href="#">Sort by name</a></p>
       <ul>
           <li ng-repeat="childItem in testTwo.childList | orderBy:testTwo.sortType">{{childItem.name}}</li>
       </ul>
   </div>
</div>

Javascript (Angular(

var app = angular.module('demo', []);
app.controller('TestController', TestController);
function TestController() {
    var vm = this;
    vm.sortType    = 'oldOrder';
    vm.sortReverse = false;
    vm.list      = [1];
    vm.childList = [{ name: 'Jimmy' },
                    { name: 'Danny' },
                    { name: 'Bobby' }];
}
/////////////////////////////////////
app.directive('tableSort', tableSort);
function tableSort() {
    var directive = {
        restrict: 'A',
        link: linkFunc,
    };
    return directive;
    function linkFunc(scope, element, attr) {
        element.on('click', function() {
            if(scope.sortType === attr.sortType) {
                scope.sortReverse = !scope.sortReverse;
            } else {
                scope.sortType = attr.sortType;
            }
        });
    }
}

JSFiddle here

我的实际应用程序有点复杂,但我试图尽可能地抽象它。

感谢您查看:)

好的 这里有几件事:

  1. 您在模板上使用控制器作为语法,但是您正在更改指令中的范围变量。因此您的控制器变量永远不会更改。

  2. 您的指令在ng-repeat内,这意味着 您实际上是在子作用域上执行,因此如果您正在设置 ng-repeat无法对范围执行的变量指令 访问它们,因为它们是在子范围之后设置的 创建。

  3. 您正在使用在 Angular 之外执行的 element.on 摘要,这意味着您必须调用 scope.$apply 才能让 角知道发生了什么事。

看看这个https://jsfiddle.net/rez8ey12/

我希望它有所帮助