Angular using $ index in ng-model

I have the following loop in which I try to increment several fields each time based on the index of the array through the loop.

<div class="individualwrapper" ng-repeat="n in [] | range:4"> <div class="iconimage"> </div> <div class="icontext"> <p>Imagine that you are in a health care facility.</p> <p>Exactly what do you think this symbol means?</p> <textarea type="text" name="interpretation_1" ng-model="interpretation_1" ng-required="true"></textarea> <p>What action you would take in response to this symbol?</p> <textarea type="text" name="action_1" ng-model="action_1" ng-required="true"></textarea> </div> </div> 

I would like to do something like this "

 ng-model="interpretation_{{$index + 1}}" 

Angular does not display this value? What would be the best way to add this logic to the mg-model field?

+8
javascript html angularjs angularjs-ng-model
source share
1 answer

It becomes an invalid expression using interpolation with the ng-model expression. You need to specify the name of the property there. Instead, you can use an object and use parenthesized notation.

ie in your controller:

 $scope.interpretation = {}; 

and in your view use it like:

 ng-model="interpretation[$index + 1]" 

Demo

 angular.module('app', []).controller('ctrl', function($scope) { $scope.interpretation = {}; $scope.actions = {}; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script> <div ng-app="app" ng-controller="ctrl"> {{interpretation}} {{actions}} <div class="individualwrapper" ng-repeat="n in [1,2,3,4]"> <div class="iconimage"> </div> <div class="icontext"> <p>Imagine that you are in a health care facility.</p> <p>Exactly what do you think this symbol means?</p> <textarea type="text" ng-attr-name="interpretation{{$index + 1}}" ng-model="interpretation[$index+1]" ng-required="true"></textarea> <p>What action you would take in response to this symbol?</p> <textarea type="text" name="action{{$index + 1}}" ng-model="actions[$index+1]" ng-required="true"></textarea> </div> </div> </div> 
+12
source share

All Articles