使用 AngularJS 从指令设置范围变量
Setting a scope variable from a directive with AngularJS
我已经在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
我的实际应用程序有点复杂,但我试图尽可能地抽象它。
感谢您查看:)
好的 这里有几件事:
-
您在模板上使用控制器作为语法,但是您正在更改指令中的范围变量。因此您的控制器变量永远不会更改。
-
您的指令在
ng-repeat
内,这意味着 您实际上是在子作用域上执行,因此如果您正在设置ng-repeat
无法对范围执行的变量指令 访问它们,因为它们是在子范围之后设置的 创建。 -
您正在使用在 Angular 之外执行的 element.on 摘要,这意味着您必须调用 scope.$apply 才能让 角知道发生了什么事。
看看这个https://jsfiddle.net/rez8ey12/
我希望它有所帮助
相关文章:
- ngDialog-弹出窗口未更新范围变量
- AngularJS范围变量Unwatch
- 将外部控制器的范围变量设置为角度
- 对于使用传递的数据计算的局部范围变量,角度绑定在自定义指令中不起作用
- 如何使用EnquireJS使AngularJS范围变量依赖于媒体查询
- 具有范围变量的控制器不工作
- 范围变量返回长度错误
- 将 NodeJS 模块范围变量作为对象访问
- Angularjs 更新 setTimeout 中的范围变量不起作用
- 递归承诺调用 - 内存范围变量问题
- AngularJS:从指令设置范围变量
- Angularjs:访问范围变量数组并计算平均值
- 范围变量更新,但不更新视图
- 从html调用angularjs控制器中的一个函数,但未定义范围变量
- 如何在编辑范围变量时(暂时)避免摘要循环
- 防止Angular范围变量通过引用自动绑定到服务私有成员
- 使用 AngularJS 从指令设置范围变量
- 集合回调忽略范围变量
- 使用forEach修改角度范围变量
- 因果报应测试中未定义的预期范围变量