I am setting a $scope.$watch over an array with nested items with the following code:
$scope.$watch("networks",
function( newValue, oldValue ) {
if(JSON.stringify(oldValue)===JSON.stringify(newValue)){
return false;
}
else if(!(angular.isUndefinedOrNull(newValue) || angular.isUndefinedOrNull(oldValue))){
var oldValueCount = 0;
var validIndexArray=[];
var newValueCount = 0;
angular.forEach(newValue, function(item,i){
if(item.isSelected=='false'){
newValueCount++;
validIndexArray.push(i);
}
});
angular.forEach(oldValue, function(item,i){
if(item.isSelected=='false'){
oldValueCount++;
}
});
console.log("oldValueCount is"+oldValueCount);
$scope.netObject = {"keyid": "","value": "","actual":""};
if(oldValueCount==newValueCount===0){return false;}
if($rootScope.planBody.length!==0){
$rootScope.planBody.campaign.networks = [];
}
angular.forEach(validIndexArray, function(item,i){
$scope.netObject.keyid=newValue[item].keyid;
$scope.netObject.value=newValue[item].value;
$scope.netObject.actual=newValue[item].actual;
$rootScope.planBody.campaign.networks.push($scope.netObject);
});
}
},
true
);
The $rootScope.planBody.campaign.networks is getting populated with duplicates of the last element I update on the view. If I select 4 items, the 4th item repeats 4 times.
When I debugged and stepped into the final function,
angular.forEach(validIndexArray, function(item,i){...});
I found something weird - after one iteration, AFTER I've pushed one $scope.netObject into $rootScope.planBody.campaign.networks, when I re-enter the loop, at the first line:
$scope.netObject.keyid=newValue[item].keyid;
The pushed item ALREADY PUSHED INSIDE $rootScope.planBody.campaign.networks gets updated with the new value. This is causing the duplication.
- Is something wrong with my code that is causing $digest to not apply? Should I be using an $apply?
- If so is that the ideal solution?
- If else, is there a better way of implementing my logic in angular?