Freewind
Freewind

Reputation: 198238

Angular.JS: why can't the inputs be edited?

This is a strange problem. The code is simple:

HTML code:

<body ng-controller="MainCtrl">
  <ul ng-repeat="name in names">
    <input type="text" ng-model="name" />
  </ul>
</body>

Angular code:

app.controller('MainCtrl', function($scope) {
    $scope.names = ["aaa","bbb","ccc"];
});

The live demo url is: http://plnkr.co/edit/2QFgRooeFUTgJOo223k9?p=preview

I do not understand why the input controls can not be edited, I can't type new characters or delete characters.

Upvotes: 9

Views: 8500

Answers (3)

PeterS
PeterS

Reputation: 2954

Late answer, but you should also be careful of typos, that angular will not warn you about:

<div ng-repeat="item in names track by $index" ng=if="names[$index] = 'John'">
    <input type="text" ng-model="names[$index]" />
</div>

Note the single equals in the ng-if, that will not cause a warning or error, but the text will also be read only. Quite a hard one to spot if you are reading quickly.

It of course should be:

<div ng-repeat="item in names track by $index" ng-if="names[$index] == 'John'">
    <input type="text" ng-model="names[$index]" />
</div>

Upvotes: 0

Pablo
Pablo

Reputation: 2386

Angular 'fixed' this in 1.1 with the track by $index. No need to change your model.

<div ng-repeat="item in names track by $index">
    <input type="text" ng-model="names[$index]" />
</div>

Plunker here

Upvotes: 3

charlietfl
charlietfl

Reputation: 171669

This is a common issue due to scope inheritance . Each of your names is a primitive so ng-repeat makes it's own scope item that is not connected to original, however if each names is an object ng-repeat scope item will be a reference to original object

 [{name:"aaa"},{name:"bbb"},{name:"ccc"}];

Always use a dot in ng-model is a helpful rule of thumb

<div ng-repeat="item in names">
      <input type="text" ng-model="item.name"/>
    </div>

Working Plunker

Read this article on angular github wiki for detailed explanaton:

https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance

Upvotes: 9

Related Questions