2014-01-05 69 views
0

一旦我意識到如何NG-模型指導工作,是絕對有信心它的行爲,這個例子只是炸飛我的腦海NG重複內角NgModelController行爲

<html ng-app> 
<head> 
    <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet"> 
</head> 
<body ng-init="names = ['Sam', 'Harry', 'Sally']"> 
    <h1>Fun with Fields and ngModel</h1> 
    <p>names: {{names}}</p> 
    <h3>Binding to each element directly:</h3> 
    <div ng-repeat="name in names"> 
     Value: {{name}} 
     <input ng-model="name">       
    </div> 
    <p class="muted">The binding does not appear to be working: the value in the model is not changed.</p> 
    <h3>Indexing into the array:</h3> 
    <div ng-repeat="name in names"> 
     Value: {{names[$index]}} 
     <input ng-model="names[$index]">       
    </div> 
    <p class="muted">Type one character, and the input field loses focus. However, the binding appears to be working correctly.</p> 
</body> 

ng-repeat fiddle。主要問題是三個不同版本的角度行爲。我明白,ng-repeat爲每個數組項目創建一個新的範圍,我想(不確定)它只跟蹤數組引用和它的大小(所以,數組項目不應該導致變化$消化循環),但是,我們有預期的行爲:用輸入改變'name'屬性只會改變ngModelController的值(範圍繼承),這是公平的,1.1.1 - 好吧,那裏發生了什麼:我們甚至沒有在輸入中獲得新的值,並且!我們不會放棄我們的項目,因爲我們不會失去焦點(我真的不明白爲什麼$ digest loop會爲這個輸入激發價值替代,因爲Artem有said),第三個版本 - 1.2.1:也改變輸入值更改外部作用域中的'name'值(因爲我理解ngModelController應該繼承由ng-repeat指令創建的作用域)。那麼,在所有三個例子中究竟發生了什麼(以及爲什麼)?

回答

0

使用Angular最新版本(1.2.1)並通過$ index進行跟蹤。此問題已修復

http://jsfiddle.net/rnw3u/55/

<div ng-repeat="name in names track by $index"> 
     Value: {{names[$index]}} 
     <input ng-model="names[$index]">       
    </div>