Changing an array inside an object displayed in ng-repeat

I am trying to update an array of $ scope objects that appears in ng-repeat on a page using input elements containing the contents of the array. An example of a plunker can be found here: demonstration of a plunger (a basic, stripped-down example of my problem)

I have the following settings object:

 $scope.settings = { list: ['list item one', 'list item two', 'list item three'] }; 

and I present the data on the page like this:

 <ul> <li ng-repeat="item in settings.list"> <input type="text" value="{{item}}" ng-model="singleItem" ng-change="settings.list[$index] = singleItem" /> <a href="javascript:void(0)">delete</a> </li> </ul> 

My goal is to initially fill the <input> fields with the contents of $scope.settings.list and whenever the element is changed, update the array, but I did not understand how to do this in the view. Omitting ng-model and ng-change at the input correctly displays the input scale in the text fields, but after that the array changes are not changed.

Side note: In the Plunker example, I have a $watch settings object. In my actual code, this is used to update the "cookie settings" with the $cookies module . In this example, cookies were omitted, but for debugging purposes, I left the clock.

+2
source share
1 answer

There are two main problems in your approach. Firstly, ngRepeat uses an inherited scope, so primitive values ​​(like strings and numbers) don't play well. You should pass arrays of objects to ngRepeat, not arrays of primitives. The second problem is a complicated way to bind to input. All you need is the following:

 $scope.settings = { list: [ { val: 'list item one'}, { val: 'list item two'}, { val: 'list item three'} ] }; 

And then, in your opinion:

 <ul> <li ng-repeat="item in settings.list"> <input type="text" ng-model="item.val"></input> <a ng-click="remove($index)">delete</a> </li> </ul> 

Here's the revised plunker: http://plnkr.co/edit/ZGFjBnVSwM4hNSgVSOCW?p=preview .

+7
source

Source: https://habr.com/ru/post/1480772/


All Articles