最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Create dynamic scope variables in AngularJs inside loop - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited May 23, 2017 at 12:10 CommunityBot 11 silver badge asked Apr 18, 2015 at 7:06 Vaibhav MagonVaibhav Magon 1,5031 gold badge14 silver badges29 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 12

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] = [];
});

You don't need $parse and assign here, just use bracket notation to access object property (because $scope is nothing but just an object) with variable name:

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

for (var i = 0; i < $scope.lists.length; i++) {
    var listName = $scope.lists[i].listName;
    $scope[listName] = [];
}
发布评论

评论列表(0)

  1. 暂无评论