How to get normalized values for an array when using ng-repeat

荒凉一梦 提交于 2019-12-08 06:02:01

问题


I am trying to get normalized value of one array associated to different groups.

http://jsfiddle.net/k5Dvj/5/

I don't want to add something new into the original array items, so I am returning new objects for normalized items for each group.

$scope.nomalizedItems = function (groupid) {
    var groupItems = $scope.originalItems.filter(function (item) {
        return item.groupid == groupid
    });

    var values = groupItems.map(function (item) {
        return item.value;
    });
    var maxValue = Math.max.apply(null, values);
    return groupItems.map(function (item) {
        return {
            id: item.id,
            normalizedValue: item.value / maxValue
        };
    });
};

I believe this logic is really simple, however angularjs is always blaming "[$rootScope:infdig] 10 $digest() iterations reached. Aborting!" even if I have added the "track by item.id" in the ng-repeat expression.

Any idea how to solve this issue? Thanks!


回答1:


ngRepeat directive is not happy. Your code creates new objects each time. Digestion loops over and over again...

From what I know, the track by expression is not supposed to make angular match the previous entities with the corresponding new ones after you erased all their internal $$hashKey properties by recreating the entities. This instruction is designed to tell ngRepeat directive how to build this internal $$hashKey to avoid DOM element creation waste.

So .. You may only alter your items instead of creating new ones:

    groupItems.forEach(function (item) {
        item.normalizedValue = item.value / maxValue;
    });
    return groupItems;

And then it works.

Moreover, your filtering is happening at each digest loop. For performance purposes, you may prefer bake this array in specific events/watchers callbacks.

UPDATE

Actually, digestion won't loop over and over again if you bake this list outside of the ngRepeat expression ! I suggest you to have a controller per group using the child scopes created by the ngRepeat directive and bake this list in a watcher callback.



来源:https://stackoverflow.com/questions/21689086/how-to-get-normalized-values-for-an-array-when-using-ng-repeat

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