Freewind Freewind - 3 months ago 6
AngularJS Question

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.

Answer

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

Comments