Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angularjs

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.

like image 355
Freewind Avatar asked Mar 30 '13 15:03

Freewind


2 Answers

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

like image 142
charlietfl Avatar answered Oct 25 '22 15:10

charlietfl


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

like image 27
Pablo Avatar answered Oct 25 '22 17:10

Pablo