2013-03-29 189 views
0

我已經花了幾個小時的時間寫了幾個小時,並重新編寫了這部分內容,如果沒有答案,我可能會在這裏編寫自己的指令。AngularJS - ngRepeat和ngModel

我有一個列輸入顯示,在6列的每一個10。我正在使用2 ngRepeat指令來顯示它們。我將6條小提琴放在下面,我試圖讓他們正確地工作。問題是,當我使用一組對象時,所有的數據都被同時更新。查看下面的提琴#1以查看示例。

下面是代碼的快速代碼片段,您也可以在小提琴頁面上看到它。如果任何人有一些指示或方法讓#1,#2或#6工作,請讓我知道!

HTML:

<div ng-controller='EntryCtrl'> 
<div class="span2" ng-repeat="a in [0,1,2,3,4,5]"> 
    <div ng-repeat="i in entry.slice($index*10, ($index*10)+10)" ng-class="{'control-group': true, error: !entry[($parent.$index*10)+$index].correct}">{{($parent.$index*10)+$index}}<input type="text" class="span12" id="entry-{{($parent.$index*10)+$index}}" ng-model="entry[($parent.$index*10)+$index].input" /></div> 
</div> 
</div> 

的Javascript:

var myApp = angular.module('myApp', []); 
myApp.controller('EntryCtrl', ['$scope', function($scope) { 
    $scope.entry=filledArray(60,{input:'',correct:true}); 
}]); 
function filledArray(len, val) { 
    var rv = new Array(len); 
    while (--len >= 0) { 
     rv[len] = val; 
    } 
    return rv; 
} 

小提琴#1:使用$index$parent.$index採用NG-模型指向的對象的數組到entryhttp://jsfiddle.net/DFEkG/ - 所有車型更新同時

小提琴#2:使用的對象數組NG-模型指向i,而不是$indexhttp://jsfiddle.net/DFEkG/1/ - 所有車型更新同時

小提琴#3:採用NG-模型指向數組到entry使用$index$parent.$indexhttp://jsfiddle.net/DFEkG/2/ - 怪異的行爲

小提琴#4陣列使用納克 - 模型指出i代替$indexhttp://jsfiddle.net/DFEkG/3/ - 破碎

Fiddle#5僅使用$index$parent.$index的數組以及僅在ng-repeat指令中的數組:http://jsfiddle.net/DFEkG/4/ - WORKS!但不能作爲對象

小提琴#6同技術5,但與對象:http://jsfiddle.net/DFEkG/5/ - 同小提琴1和2

回答

1

的問題是在你filledArray功能。它爲每個數組項目分配相同的確切對象。所有60個實例中都引用了相同的對象{input: '', correct: true}

因此,要解決它,你可以簡單地在每次迭代的一個新副本:

function filledArray(len, val) { 
    var rv = new Array(len); 
    while (--len >= 0) { 
     rv[len] = angular.copy(val); 
    } 
    return rv; 
} 

Fiddle

+0

天才。我從來不會認爲這是問題。 –