如果我尝试执行 ng-repeat 以将某些字段数据绑定(bind)到数组,例如使用 $index
值,则输入会在 1 次击键后自动模糊。查看示例以了解我的意思。
(使用 angular stable 1.2.4 和最新版本:1.2.5 和来自 jsfiddle 的 1.1.1 进行测试)
( fiddle :http://jsfiddle.net/Dj4n4/)
或者下面的 html,同样的事情
<!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>
最佳答案
我从 AngularJS Google Groups 的 Michael Hard 那里得到了很好的回答:
https://groups.google.com/forum/#!topic/angular/q1U-9Dj7leU
解决方案是使用 Angular >= 1.2.4(当前稳定的版本)并在 ng-repeat
中使用 track by
,又名:
<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>
关于javascript - 一次击键后Angularjs ng-repeat输入模糊,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20446196/