【问题标题】:Angular filter running more times than expectedAngular 过滤器的运行次数超出预期
【发布时间】:2016-04-07 13:26:57
【问题描述】:

我做了一个过滤器来按类别对问题进行排序。

我试图弄清楚为什么我的 Angular 过滤器运行的次数比输入值多。

第一个问题:在填充问题之前运行过滤器:

当存在问题对象时再次运行:

第二个问题: 我的指令的scope.questions 数组只包含一个问题对象,但过滤器运行了6 次?这是为什么呢?

指令 HTML sn-p:

    <div class="category-filter">
        <div ng-repeat="(k, v) in catfilters" class="question">
            <input type="checkbox" ng-init="checked=true" ng-model="catfilters[k]">{{ k }}
        </div>
    </div>

循环:

    <div class="question-category">
        <li ng-repeat="q in questions | bycategory:catfilters" class="question">
            {{q.question.category.category}}
        </li>
    </div>

指令JS:sn-p

    scope.questions = args;

    console.log(scope.questions.length); //Length == 1
    /*
        Dynamically add question filters
     */
    scope.questions.forEach(function (k, v) {
        scope.catfilters[k.question.category.category] = true;
    });

过滤器:

    filter('bycategory', function() {
        return function (questions, catfilterObj) {

            console.log('Q', questions); // Called 6 times

            var items = {
                categories: catfilterObj,
                out: []
            };

            angular.forEach(questions, function (value, key) {
                if (this.categories[value.question.cat_id] === true) {
                    this.out.push(value);
                }
            }, items);
            return items.out;
        };
    }

【问题讨论】:

  • 您所看到的是角度摘要的工作原理。它们至少运行 2 次,直到范围稳定,如果从摘要中检测到范围更改,则运行更多次。
  • @charlietfl 有没有办法提高效率?对于包含单个对象的数组来说,6 次调用是非常核心的
  • 是否会导致性能问题?
  • 在过滤器上运行 6 次甚至可能不是所显示元素的结果...它可能与 html 的其他部分也被消化有关。
  • @Growler 除非您的多个用户在同一台​​机器上同时使用同一个浏览器,否则我不认为用户数量会成为问题。

标签: javascript angularjs


【解决方案1】:

正如@charlietfl 指出的那样,您的角度表达式将继续被调用,直到范围稳定。

除非您发现它会导致性能问题,否则不必担心,但如果您担心,您可以在过滤器中消除一些不必要的操作:

filter('bycategory', function() {
    return function (questions, catfilterObj) {

        console.log('Q', questions); // Called 6 times

        return Array.prototype.filter.call(questions, function (value) {
            return catfilterObj[value.question.cat_id] === true;
        });
    };
})

【讨论】:

    猜你喜欢
    • 2017-03-31
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多