DonJuwe
DonJuwe

Reputation: 4563

Bind input model to every object in array

I have a simple input like this:

<input type="text" ng-model="myModel" />

and an array in my controller like this:

myApp.controller('MyCtrl', function($scope) {
    $scope.arr = [
        {str: ''},
        {str: ''}
    ];
});

How to bind my inputs model to the str attribute of every single object in my arr?

Fiddle here.

Thanks for your help.

Upvotes: 1

Views: 132

Answers (1)

Rayon
Rayon

Reputation: 36609

Use ng-change directive and update the scope using angular.forEach

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope) {
  $scope.arr = [{
    str: ''
  }, {
    str: ''
  }];
  $scope.updateIt = function(myModel) {
    angular.forEach($scope.arr, function(value, key) {
      value.str = myModel;
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>

<div ng-app="myApp" ng-controller="MyCtrl">
  <code>{{arr}}</code>
  <br />
  <br />
  <!-- bind input model to every object 'str' -->
  <input type="text" ng-model="myModel" ng-change='updateIt(myModel)' />
</div>

Fiddle Demo

Upvotes: 1

Related Questions