1

Problem 1:

I came across this issue where in I need to create objects on the fly based on a loop.

Example:

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

Am I approaching this the wrong way? Can I create $scope.element based on an index?

Problem 2:

I also notice that in the HTML if you do something like:

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

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?

Thanks

1
  • Could you elaborate what you are trying to accomplish by adding these properties on the fly? Commented May 16, 2013 at 2:01

1 Answer 1

1

Problem 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();
});

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Mark. the first part works like a charm. I would've never guessed that one. The second one is still confusing to me, since all I have access to is the HTML. I will love to see if I can put together an object with the correct name by using the $index as part of the name. Can it be done in the HTML?
Awesome. Thank you Mark for adding the fiddle.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.