AngularJS ng-repeat和ng-model与textarea/input标签不相配



当我使用 ng-repeat 生成输入标签并在自定义指令中分配 ng-model 时它在每次击键时调用指令。

这是演示

http://plnkr.co/edit/Oku8EH?p=preview

var app = angular.module('myApp', []);
app.controller('MyCtrl', function($scope) {
  $scope.arr = ["1234567"];
});
app.directive('myDirective', function($compile, $timeout) {
  var num=0;
  return {
    link: function(scope, el, attrs) {
      console.log('this happens with every keyup event in textarea when ng-model is given as arr[$index], why?');
    }
  };
});

<body ng-app="myApp" ng-controller="MyCtrl">
  arr[0] : {{arr[0]}} <br/>
  <input my-directive ng-repeat="str in arr" ng-model="arr[$index]" />
  </input>
</body>

很奇怪。

这是因为每次您更改arr数组时,ng-repeat都会重新评估,因为它必须监视它(请参阅Github上ngRepeat源中的l256行)

如果将模型指向另一个数组,则一切正常。

你可以用这个Plunkr来检查一下。

最新更新