How to dynamically add input rows to view and maintain value in angularjs ng-model as array item

放肆的年华 提交于 2019-12-04 20:41:06

The first problem is with the binding on the input boxes. Due to the ng-repeat surrounding the input box, each input box has an item value available to bind to, and that is what your ng-model should be. You shouldn't be assigning anything to the value attribute.

<input ng-model="item.value" type="text"  size="40">

Making that change will at least get the input boxes to display the items. But typing in the boxes won't update the underlying array. That's the second problem.

The ng-repeat directive prototypically inherits the scope from your controller (read more about scope here). Since your items are primitive strings, the elements in your ng-repeat effectively get copies of the data from the controller, and typing in the boxes updates those copies, not the actual data in the controller.

To fix this, just make your items an array of objects instead of an array of strings.

$scope.items = [
  {value:'First Item'},
  {value: 'Second Item'}
];

Then you would bind your textboxes like this:

<input ng-model="item.value" type="text"  size="40">

Here's a Plunker showing how it works.

This certainly is possible, check out this updated plnkr

I updated your array to be an array of objects (not strings) with a property of text and changed your inputs to this:

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