2013-03-30 95 views
9

这是一个奇怪的问题。代码很简单:Angular.JS:为什么不能编辑输入?

HTML代码:

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

角码:

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

的现场演示网址为:http://plnkr.co/edit/2QFgRooeFUTgJOo223k9?p=preview

我不明白,为什么输入控件不能被编辑,我不能输入新的字符或删除字符。

回答

9

由于范围继承,这是一个常见问题。您的每一个names的是一种原始,所以ng-repeat使得未连接到原来它自己的范围内的项目,但如果每个names是一个对象ng-repeat范围的项目将是原来的对象的引用

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

始终使用在dotng-model拇指是一个有用的规则

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

Working Plunker

阅读这篇文章,对角GITH UB维基详细explanaton:

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

3

角在1.1 '固定' 这个由$指数的轨道。无需改变你的模型。

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

Plunker here

0

晚的答案,但你也应该小心错别字,那角不会警告你:

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

注单等于在NG-IF,即不会导致警告或错误,但文字也将只读。如果你正在快速阅读,很难发现。

当然它应该是:

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

您的修正缺少修正。 =] – sonicblis

+0

@sonicblis好点,更正! – PeterS