使用angularjs动态创建对象

时间:2013-05-16 01:16:24

标签: angularjs

问题1:

我遇到过这个问题,我需要根据循环动态创建对象。

示例:

angular.forEach([0,1,2], function (index) {
    $scope.cc + index = buildMeProto();
});

我接近这个错误的方式吗?我可以根据索引创建$scope.element吗?

问题2:

我还注意到在HTML中,如果你做了类似的事情:

<div ng-repeat="black in blacks">
    <lightbox name="black+$index" />
</div>

你不能在对象上追加索引,在这种情况下,'black'是一个对象,索引是0,1,2等。

是否有各种方法来搭载索引以创建或调用元素?

由于

1 个答案:

答案 0 :(得分:1)

问题1

如果您想动态创建$scope属性,则需要使用[]表示法。

angular.forEach([0,1,2], function (index) {
    $scope["cc" + index] = buildMeProto();
});

问题2 您可以通过添加属性来调用范围上的函数来扩充对象。

$scope.addIndex = function(person, index){
    person.id = index;
};

<强> Example jsfiddle.