gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 15:29:15 25 4
gpt4 key购买 nike

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

目标是根据指令的“sort-type”属性中提供的属性对名称列表进行排序,但仅针对每个 Controller 中的列表(并非同时所有列表)。

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. 您在模板中使用了 controllerAs 语法,但是您正在更改指令中的范围变量。因此你的 Controller 变量永远不会改变。

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

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

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

希望对你有帮助

关于javascript - 使用 AngularJS 从指令设置范围变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36464716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com