使用AngularJS指令设置作用域变量

3
我已经查阅了在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

我的实际应用程序有些复杂,但我已尽可能地将其抽象化。

谢谢您的关注 :)

1个回答

1

好的,这里有几个问题:

  1. 你在模板中使用了controllerAs语法,但是在指令中改变了scope变量。因此,你的controller变量从未被改变。

  2. 你的指令位于ng-repeat中,这意味着你实际上正在操作子作用域,因此如果你在作用域上设置变量,则ng-repeat将无法访问它们,因为它们是在创建子作用域之后设置的。

  3. 你使用了element.on,这在angular digest之外执行,这意味着你必须调用scope.$apply才能让angular知道发生了什么事情。

看一下这个https://jsfiddle.net/rez8ey12/,希望对你有所帮助。


这对我来说非常有效。感谢您抽出时间帮助! - Daan Geerdink

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接