与angularjs动态创建对象 [英] create objects on the fly with angularjs
问题描述
问题1:
我碰到这个问题在哪里,我需要基于一个循环动态创建的对象。
I came across this issue where in I need to create objects on the fly based on a loop.
例如:
angular.forEach([0,1,2], function (index) {
$scope.cc + index = buildMeProto();
});
我是不是接近这个错误的方式?我可以创建 $ scope.element
基于一个指标?
问题2:
我也注意到,在HTML,如果你做这样的事情:
I also notice that in the HTML if you do something like:
<div ng-repeat="black in blacks">
<lightbox name="black+$index" />
</div>
可以不是索引附加到一个对象,在这种情况下,黑是一个对象,索引是0,1,2等
you can't append an index to an object, in this case 'black' is an object and index is 0, 1,2 etc.
有没有每个方法来骑小猪索引创建或调用元素?
Is there a each way to piggy ride the index to create or invoke elements?
感谢
推荐答案
问题1
如果你想创建一个 $范围上,你需要使用
属性。 []
符号飞
If you want to create a $scope
property on the fly you need to use the []
notation.
angular.forEach([0,1,2], function (index) {
$scope["cc" + index] = buildMeProto();
});
问题2
你可以致电范围的功能,将通过增加一个属性增强的对象。
Problem 2 You could call a function on the scope that would augment the object by adding a property.
$scope.addIndex = function(person, index){
person.id = index;
};
Example jsfiddle.
这篇关于与angularjs动态创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!