angularjs ng-repeat use $index inside ng-model directive

心已入冬 提交于 2019-12-02 06:57:34

问题


Try to use ng-repeat

<ul>
    <li ng-repeat = "n in [1,2,3,4]>

     <label id="{{'p'+ n }}"> {{n}} </label>
     <label ng-model="{{'p'+ n }}"> {{n}} </label>

     </li>

</ul>

The first "label" works. Its "id" is assigned properly. But the second "label" doesn't work.

Is that because "ng-model" cannot be created dynamically?

I was trying to use <select ng-model ... ng-options ...> within a ng-repeat. Not being able to create these "ng-model" dynamically, I am stuck here.


回答1:


ng-model is an Angular attribute, you don't need to include the {{}} -- try ng-model="'p' + n"




回答2:


Try using ng-init to reference $index

<li ng-repeat = "n in [1,2,3,4] ng-init="myIndex = $index">
  <label ng-model="{{'p'+ myIndex }}" />
</li>



回答3:


This is not working because you have used ng-model on label tag which is not possible.

ng-model can be only used on input, select and textarea as per This

you cannot use it on div's, ul, ol, tabel etc.

Instead, to assign the value in label you can use ng-value like this:

<label ng-value="{{'p'+ n }}"> {{n}} </label>

or to assign index value to ng-model you can do:

<input type="text" ng-model="user.text[$index]"/>

to display the index you can do:

{{$index}}


来源:https://stackoverflow.com/questions/21789833/angularjs-ng-repeat-use-index-inside-ng-model-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!