1

I have an ng-repeat div that I need to use the $index variable to build out an expression. Consider the following:

<div ng-repeat="item in myItems track by $index">
   This will throw an error: {{myItemId_{{$index}}.someProperty}}
</div>

If I have a $scope variable called "myItemId_0", how do I use $index within a curly braces {{}} expression? I have tried omitting the curly braces for the $index variable, this but this doesn't work either:

{{myItemId_$index.someProperty}}

2
  • I don't have much to add to the answers below, but here's how I'd go about it. codepen.io/anon/pen/vNNBgj Commented Sep 9, 2015 at 19:42
  • do you also have a {{myItemId_{{$index}} for all $index values? Commented Sep 9, 2015 at 19:45

1 Answer 1

4

Since it's a variable on scope, create a function that retrieves your property via bracket notation.

HTML:

{{getByIndex($index, "someProperty")}}

Controller:

$scope.getByIndex = function(index, someProperty) {
    var propertyName = "myItemId_" + index;

    return $scope[propertyName][someProperty];
}

However, the logical solution is to not access your properties in this way at all, but rather use item which is already available from your ng-repeat.

HTML:

div ng-repeat="item in betterItems track by $index">
    {{item.someProperty}}
</div>

Controller:

$scope.betterItems = [];
angular.forEach(myItems, function (i) {
    $scope.betterItems.push(createMappedItem(i));
}

Even if you have to map your collection to a new collection (or reuse the same if need be), you can still access that original item. It's cleaner and much easier to maintain. In addition, retrieval by index can be very dangerous if you start mutating the collection.

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

2 Comments

This is the better answer. You shouldn't have a bunch of foo_1, foo_2, foo_N variables in your scope.
@Agop agreed, although at times there are extenuating circumstances that prevent you for doing so, for whatever reason. However, if you can avoid that type of maintenance nightmare, you'll always be better off :).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.