0

When I generate input tags with ng-repeat and assign ng-model within custom directive it invokes directive on every key stroke.

This is Demo

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>

It's strange.

allenhwkim
  • 27,270
  • 18
  • 89
  • 122

1 Answers1

1

It's because the ng-repeat is reevaluating each time you change the arr Array as it must be watching it (see line l256 here in ngRepeat sources on Github)

If you point the model on another array, everything is OK.

You can check it out with this Plunkr.

allenhwkim
  • 27,270
  • 18
  • 89
  • 122
ThomasC
  • 7,915
  • 2
  • 26
  • 26
  • Also may want to check out: http://stackoverflow.com/questions/13651578/how-to-unwatch-an-expression Which explains how To have a repeater with a large array that you don't want to watch every item. – TheSharpieOne Jan 09 '14 at 16:39
  • I tried `str in arr track by $index`, message is not happening. How does it different? – allenhwkim Jan 09 '14 at 18:39