I am trying to get normalized value of one array associated to different groups.
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!
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