Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
-1
rated 0 times [  5] [ 6]  / answers: 1 / hits: 17152  / 9 Years ago, sat, april 18, 2015, 12:00:00

I am new to Angular.js and am trying to create dynamic scope variables in AngularJs inside a for Loop. This is something as below:



$scope.lists=[{listName:'list1'},{listName:'list2'}];

for(var i=0;i<$scope.lists.length;i++){
var listName = $scope.lists[i].listName;
listName = $parse(listName);
listName.assign($scope,[]);
$scope.$apply();
}


The above code throws an error saying: $digest already in progress.



The code works ok when used without looping just for one as done in:
Setting dynamic scope variables in AngularJs - scope.<some_string>



I ultimately am looking for $scope.list1=[] and $scope.list2=[] as 2 separate arrays.



Any leads would be awesome. Thanks.


More From » angularjs

 Answers
21

The above code throws an error saying: $digest already in progress.




You're already in the controller and in angular scope. So no need to trigger the digest loop using $scope.$apply(). Even if you have to must check the $$phase and then apply.



if (!$scope.$$phase) $scope.$apply()


But for your scenario, it's not required at all



$scope.lists = [{listName: 'list1'}, {listName: 'list2'}];

angular.forEach($scope.lists, function(item) {
var listName = item.listName;
$scope[listName] = [];
});

[#67022] Thursday, April 16, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
karivictoriab

Total Points: 530
Total Questions: 90
Total Answers: 95

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
;