在指令属性上使用过滤器会导致 $digest 循环中的无限循环 [英] Using filter on directive attribute causes infinite loop in $digest cycle

查看:13
本文介绍了在指令属性上使用过滤器会导致 $digest 循环中的无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在具有隔离范围的指令上使用过滤器:

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

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

导致$digest循环无限循环:

Causes an infinite loop in the $digest cycle:

当应用程序的模型变得不稳定并且每个 $digest 循环都会触发状态更改和后续的 $digest 循环时,会发生此错误.Angular 会检测到这种情况并防止无限循环导致浏览器无响应.

.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

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

这种行为正常吗?

  1. 不能对传入指令隔离范围的值使用过滤器吗?
  2. 有解决办法吗?我需要过滤数组值
  3. 还有其他设计不同的解决方案吗?

推荐答案

我觉得不是指令问题,而是过滤器问题.过滤器的目标是获取一个数组作为输入,并根据一些规则和条件返回另一个数组,其中数组项与输入具有相同的结构.

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.

导致$digest循环无限循环的原因是在一个过滤器中,每个摘要循环过滤器返回一个不同的对象,导致一个额外的循环.

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.

我建议你从返回相同的数组开始,即 input = output.检查是否一切都按预期工作.之后添加相关条件.

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.

这篇关于在指令属性上使用过滤器会导致 $digest 循环中的无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆