Mohammad Sadiqur Rahman Mohammad Sadiqur Rahman - 10 days ago 6
AngularJS Question

How to trigger Dynamic ng-model from controller?

I run a loop in my html and each iteration there will be dynamically model created.

<tr ng-repeat="item in voucherItems">
<td><input type="text" ng-model="this['id-' + $index]" typeahead="brand.id as brand.BRANDNAME for brand in brandList" class="input-group" /></td>

</tr>


model will be like id1,id2,id3 etc.
Now i want to use that dynamic model in my angular controller.

function GetValue(indexno) {
var model=scope."id"+indexno;
dosomething(model);
}


the value of var model will be the value of scope.id1 or scope.id2 or scope.id3 as created in html.Now the problem is


scope."id"+indexno


does not work like scope.id1 or scope.id2 or scope.id3 which will be the dynamic model rather it's showing error.Question is how can i write this quoted part in angular controller which will be work like scope.id1 or scope.id2 or How can i trigger that model dynamically?

Answer

finally got it.In html

ng-model=id[$index]

in controller.I have to declare first

scope.id={};

then in the GetValue method

function GetValue(indexno) {
      var model=scope.id[indexno];
      dosomething(model);
 }

that works for me. scope.id[indexno] working like scope.id1 or scope.id2 etc.Thanks to @Nora and @gianlucatursi.

OBSERVATION You can declare scope.id=[] instead of scope.id={} it will work also.