AngularJS: ng-model setter inside ng-repeat

I found some excellent answers on how to get the ng-model value inside ng-repeat , but so far I have not found that this covers the setter. Suppose I have something like this:

 <div ng-repeat="item in getItems()"> <input ng-model="itemTitle" ng-model-options={getterSetter:true}"> </div> 

If I had one input window, I would use something like this :

 ... var _val = ''; $scope.itemTitle = function(val){ return angular.isDefined(val) ? (_val = val) : _val; } ... 

However, this will change the value for each individual input window. Is it possible to define variables and setter, potentially using arrays? Or is there a better way to get and set input fields inside ng-repeat?

+5
source share
2 answers

answer from Wayne Ellery answers the question as it shows "the best way to get and set input fields inside ng-repeat".

However, if you really want to use ng-model-options="{getterSetter: true}" inside ng-repeat , as implied in the question and comments, then this is a little more complicated, because in your getterSetter function you do not know which element from ng-repeat .

Essentially, you need to pass a different getter / setter function for each element, and you can do this by passing an ng-model function that will create the getter / setter element specific to you.

 <div ng-app="app" ng-controller="ctrl"> <div ng-repeat='row in items'> <span>{{row.name}}</span> <input type='text' ng-model='createTitleGetterSetter(row.name)' ng-model-options='{ getterSetter: true }' /> </div> <hr/> <pre>{{ itemTitles | json }}</pre> </div> 

And the JS code:

 var app = angular.module('app',[]); app.controller('ctrl', function($scope) { $scope.items = [ {'name': 'a'}, {'name': 'b'}, {'name': 'c'} ]; $scope.itemTitles = {}; $scope.createTitleGetterSetter = function(name) { if (!$scope.itemTitles[name]) { $scope.itemTitles[name] = { getterSetter: function(newValue) { return arguments.length === 0 ? $scope.itemTitles[name].title : $scope.itemTitles[name].title = newValue; }, title: '' } } return $scope.itemTitles[name].getterSetter; }; }); 

JSFiddle here: http://jsfiddle.net/zLg3mLd0/1/

In this case, the headings of the elements, of course, are not saved along with the objects of the object (if you wanted it, just ng-model enough), but in the itemTitles map.

Confirm this answer and its comments, for which this answer is largely based.

+5
source

You must set ng-model to item.title so that every object in the array returned from getItems() contains a title .

 <div ng-repeat="item in getItems()"> <input type="text" ng-model="item.title"/> </div> 
+2
source

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


All Articles