Angularjs ng-repeat blur input after one keystroke

If I try to execute ng-repeat to bind some fields to an array, for example, using a value $index, then the input is automatically erased after 1 key press. Check out the example to find out what I mean.

(tested with angular stable 1.2.4 and the latest: 1.2.5 and 1.1.1 from jsfiddle)

(script: http://jsfiddle.net/Dj4n4/ )

or html below the same

<!doctype html>
<html ng-app>
  <head>
    <script src="js/angular.js"></script>
    <script type="text/javascript">
      function testController ($scope) {
        $scope.data = {
          a: 1,
          b: '2222',
          c: {
            d: 3,
            e: [1, 2, 3],
          }
        };
      }
    </script>
  </head>

  <body ng-controller="testController">
    Works: <label><input type="text" ng-model="data.c.e[1]" /></label>
    <br />
    Blurs after one keystroke:
    <label ng-repeat="no in data.c.e">
      <input type="text" ng-model="data.c.e[$index]" />
    </label>
    <pre>{{data | json}}</pre>
  </body>
</html>
+4
source share
2 answers

I got a great answer from Michael Hard in Google AngularJS groups:

https://groups.google.com/forum/#!topic/angular/q1U-9Dj7leU

Angular >= 1.2.4 ( ) track by ng-repeat, aka:

<label ng-repeat="no in data.c.e track by $index">

:

<!doctype html>
<html ng-app>
  <head>
    <script src="js/angular.js"></script>
    <script type="text/javascript">
      function testController ($scope) {
        $scope.data = {
          a: 1,
          b: '2222',
          c: {
            d: 3,
            e: [1, 2, 3],
          }
        };
      }
    </script>
  </head>

  <body ng-controller="testController">
    Works: <label><input type="text" ng-model="data.c.e[1]" /></label>
    <br />
    Blurs after one keystroke:
    <label ng-repeat="no in data.c.e track by $index">
      <input type="text" ng-model="data.c.e[$index]" />
    </label>
    <pre>{{data | json}}</pre>
  </body>
</html>
+4

, ng-repeat . , :

f: [{no:1},{no:2},{no:3}]
// ...
<input type="text" ng-model="data.c.f[$index].no" />

Fiddle

- .

$scope.$watch("data.c.f", function(){
    $scope.data.c.e = [];
    $scope.data.c.f.forEach(function(obj){
        $scope.data.c.e.push(obj.no);
    })
}, true)
+1

All Articles