将输入模型绑定到数组中的每个对象

时间:2016-06-27 13:41:44

标签: javascript angularjs data-binding angular-ngmodel angularjs-ng-model

我有一个像这样的简单input

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

和我的控制器中的数组如下:

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

如何将input模型绑定到str中每个对象的arr属性?

Fiddle here.

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

  

使用ng-change指令并使用scope

更新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