简体   繁体   中英

How to construct scope variables dynamically in angular view?

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 ?

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>

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,

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? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM