Using filter on directive attribute causes infinite loop in $digest cycle

牧云@^-^@ 提交于 2019-12-20 02:52:19

问题


An attempt to use a filter on a directive with isolate scope:

<div tags="p.tags | refTags"></div>

Causes an infinite loop in the $digest cycle:

This error occurs when the application's model becomes unstable and each $digest cycle triggers a state change and subsequent $digest cycle. Angular detects this situation and prevents an infinite loop from causing the browser to become unresponsive.

.directive 'tags', ->
    restrict: 'A'
    scope:
        tags: '='
    templateUrl: 'partials/tags.html'


.filter 'refTags', ->
    (tags) ->
        ['a filtered', 'array of values']

partials/tags.html

<ul>
    <li ng-repeat="tag in tags">{{tag.tag}}</li>
</ul>

p.tags in the controller

p.tags = ['HTML5', 'CSS', 'JavaScript', 'Angular JS', 'Backbone JS', 'Node JS', 'SASS + Compass', 'Oragami', 'Running', 'Cat Food', '#catfood']

Is this behavior normal?

  1. Can a filter not be use on a value passing in to the isolate scope of a directive?
  2. Is there a workaround for this? I need to filter the arrays values
  3. Is there another solution with a different design?

回答1:


I don't think it is a directive problem but a filter problem. The goal of filter is to get an array as input and return another array based on some rules and conditions, where array items have the same structure as input.

The reason that causes an infinite loop in the $digest cycle is that in a filter, each digest cycle filter returns a different object that causes an additional cycle.

I suggest you to start by returning the same array, i.e. input = output. Check if all works as expected. After that add the relevant condition.




回答2:


This question provides an actual workaround.

In short, pass the filter you want to use into your directive as well, and then use it there.



来源:https://stackoverflow.com/questions/21100108/using-filter-on-directive-attribute-causes-infinite-loop-in-digest-cycle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!