javascript 在循环内的 AngularJs 中创建动态范围变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29714134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create dynamic scope variables in AngularJs inside loop
提问by Vaibhav Magon
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:
我是 Angular.js 的新手,正在尝试在 AngularJs 中的 for 循环中创建动态范围变量。这是如下内容:
$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.
上面的代码抛出一个错误说:$digest
已经在进行中。
The code works ok when used without looping just for one as done in: Setting dynamic scope variables in AngularJs - scope.<some_string>
代码在不循环的情况下使用时可以正常工作,如: Setting dynamic scope variables in AngularJs - scope.<some_string>
I ultimately am looking for $scope.list1=[]
and $scope.list2=[]
as 2 separate arrays.
我最终正在寻找$scope.list1=[]
和$scope.list2=[]
作为 2 个单独的数组。
Any leads would be awesome. Thanks.
任何线索都会很棒。谢谢。
回答by mohamedrias
The above code throws an error saying: $digest already in progress.
上面的代码抛出一个错误说:$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.
您已经在控制器和角度范围内。因此无需使用$scope.$apply()
. 即使你必须检查$$phase
,然后申请。
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] = [];
});
回答by dfsq
You don't need $parse
and assign
here, just use bracket notationto access object property (because $scope
is nothing but just an object) with variable name:
您不需要$parse
,assign
在这里,只需使用括号表示法来访问$scope
具有变量名称的对象属性(因为它只是一个对象):
$scope.lists = [{listName: 'list1'}, {listName: 'list2'}];
for (var i = 0; i < $scope.lists.length; i++) {
var listName = $scope.lists[i].listName;
$scope[listName] = [];
}