本文介绍了Angular.js 将过滤器传递给指令双向 ('=') 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在页面的几个地方使用 sublist
指令,它有时应该包含完整的 fields
列表,但有时会被过滤.这是我天真的方法:
HTML:
<sublist fields="fields"/><!-- 这个没问题--><sublist fields="fields | filter: 'Rumba'"/><!-- 这个会引发错误-->
Javascript:
angular.module('myApp', []).directive('sublist', function () {返回 {限制:'E',范围:{字段:'='},模板:'<div ng-repeat="f in fields">{{f}}</div>'};}).controller('MainCtrl', function($scope) {$scope.fields = ['桑巴', '伦巴', '恰恰恰恰'];});
http://jsfiddle.net/GDfxd/14/
当我尝试使用过滤器时出现此错误:
错误:已达到 10 次 $digest() 迭代.中止!
这个问题有解决方案吗?
解决方案
$digest iterations 错误通常发生在观察者更改模型时.在错误情况下,隔离 fields
绑定绑定到过滤器的结果.该绑定创建了一个观察者.由于过滤器每次运行时都会从函数调用中返回一个新对象,因此它会导致观察者不断触发,因为旧值永远不会与新值匹配(参见 此评论来自 Google 网上论坛中的 Igor).
一个好的解决方法是在两种情况下绑定 fields
,例如:
并为第二种情况添加另一个可选属性以进行过滤:
然后调整您的指令,如:
return {限制:'E',范围: {字段:'=',过滤器:'='},模板:'<div ng-repeat="f in fields | filter:filterBy">'+'<small>我在这里:</small>{{f}}
'};
注意:记得关闭你的小提琴中的 sublist
标签.
这是一个小提琴
I need to use sublist
directive in few places of the page, and it should contain sometimes full fields
list, but sometimes filtered. Here is my naive approach:
HTML:
<div ng-controller="MainCtrl">
<sublist fields="fields" /> <!-- This one is OK -->
<sublist fields="fields | filter: 'Rumba'" /> <!-- This one raises error -->
</div>
Javascript:
angular.module('myApp', [])
.directive('sublist', function () {
return {
restrict: 'E',
scope: { fields: '=' },
template: '<div ng-repeat="f in fields">{{f}}</div>'
};
})
.controller('MainCtrl', function($scope) {
$scope.fields = ['Samba', 'Rumba', 'Cha cha cha'];
});
http://jsfiddle.net/GDfxd/14/
When I try to use filter I'm getting this error:
Error: 10 $digest() iterations reached. Aborting!
Is there a solution for this problem?
解决方案
The $digest iterations error typically happens when there is a watcher that changes the model. In the error case, the isolate fields
binding is bound to the result of a filter. That binding creates a watcher. Since the filter returns a new object from a function invocation each time it runs, it causes the watcher to continually trigger, because the old value never matches the new (See this comment from Igor in Google Groups).
A good fix would be to bind fields
in both cases like:
<sublist fields="fields" /></sublist>
And add another optional attribute to the second case for filtering:
<sublist fields="fields" filter-by="'Rumba'" /></sublist>
Then adjust your directive like:
return {
restrict: 'E',
scope: {
fields: '=',
filterBy: '='
},
template: '<div ng-repeat="f in fields | filter:filterBy">'+
'<small>here i am:</small> {{f}}</div>'
};
Note: Remember to close your sublist
tags in your fiddle.
Here is a fiddle
这篇关于Angular.js 将过滤器传递给指令双向 ('=') 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!