1

Suppose, I have :

$scope.head1="abc";
$scope.head2="bfc";
...
...
$scope.head12="bfc";

and, I do this :

<div ng-repeat="count in [3,4,5,6,7,8,9,10,11,12]" class="padding-top-10">
  <span>{{head + count}}</span>
</div>

I want to get the values of head1, head2, head3.. head12 in the div. How to do that ?

1
  • 1
    can't you create an array with the values of head1 head2 etc and simply display the values in the array? Commented Mar 23, 2017 at 14:36

3 Answers 3

3

Any reason you're not doing this?

$scope.head = ["abc", "bfc", ..., "bfc"];

View:

<div ng-repeat="count in [3,4,5,6,7,8,9,10,11,12]" class="padding-top-10">
  <span>{{ head[count - 1] }}</span>
</div>

If that's not an option, you can define this method:

$scope.getHead = function (num) {
    return $scope["head" + num];
};

And then:

<div ng-repeat="count in [3,4,5,6,7,8,9,10,11,12]" class="padding-top-10">
  <span>{{ getHead(count) }}</span>
</div>
Sign up to request clarification or add additional context in comments.

Comments

1

You can do this

<div ng-repeat="count in [1,2,3,4,5,6,7,8,9]" class="padding-top-10">
       <span>{{$parent['head'+count]}}</span>
   </div>
</body>

Like this you do not need an extra scope function to get the values from your scope variables. $parent is necessary because your ng-repeat creates its own scope.

angular docs--> ngRepeat - directive in module ng The ngRepeat directive instantiates a template once per item from a collection. Each template instance gets its own scope,

Comments

1

Use property accessor bracket notation with the this context keyword:

<div ng-repeat="count in [3,4,5,6,7,8,9,10,11,12]" class="padding-top-10">
  <span>{{this["head"+count]}}</span>
</div>

With Angular Expressions the this keyword evaluates to the $scope of the expression.

Be aware that the ng-repeat directive creates child scopes and that this expression finds the value by prototypical inheritance. This can cause problems when using this in ng-model directives. (This issue with primitives can be easily avoided by following the "best practice" of always have a '.' in your ng-models)

For more information, see What are the nuances of scope prototypal / prototypical inheritance in AngularJS?.

Comments

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.