2015-06-13 40 views
1

我收到了'Repeater in repeater'錯誤。我讀了一些我可以通過索引進行跟蹤的地方,但只要我這樣做,我的所有對象標題和描述值就會變得重複。我需要爲每個步驟定義獨特的標題,描述和資產數組。我怎樣才能做到這一點?ng-repeat with empty objects

var stepTemplate = { 
     assets:[] 
    } 
$scope.item.steps = [stepTemplate]; 


$scope.addRow = function(){ 
     $scope.item.steps.push(stepTemplate); 
     $log.debug('row added') 
    } 
    $scope.deleteRow = function(index){ 
     $scope.item.steps.splice(index, 1); 
     $log.debug('row deleted') 
    } 
    $scope.addAsset = function(index){ 
     $scope.item.steps[index].assets.push({'type':'textfile'}); 

    } 
    $scope.deleteAsset = function(index){ 
     $scope.item.steps[index].assets.splice(index, 1); 

    } 




<div class="row" ng-repeat="step in item.steps"> 
    <div class="well"> 

     <button class="btn btn-danger pull-right" ng-click="deleteRow($index)">-</button> 
     <input type="text" ng-model="step[$index].title" name="{{field}}" class="form-control"> 
     <textarea rows="7" ng-model="step[$index].desc" name="{{field}}" class="form-control"></textarea> 

      Add Assets 
      <div class="row" ng-repeat="asset in step.assets"> 
       <!--asset html --> 
      </div> 
     <button class="btn btn-primary pull-right" ng-click="addAsset($index)">+</button> 
     <button class="btn btn-primary pull-right" ng-click="deleteAsset($index)">-</button> 
    </div> 
</div> 

回答

1

這是因爲您每次都向數組添加相同的對象實例(stepTemplate)。 Angular認爲該數組有多個條目,但它們都指向相同的對象實例。

這裏的解決方案是創建您的模板的副本,並將副本添加到數組,而不是模板本身。您可以使用angular.copy()創建深層副本。

$scope.addRow = function() { 
    // create a deep copy of the step template 
    var newStep = angular.copy(stepTemplate); 

    // make any updates to it if necessary 
    newStep.foo = 'bar'; 

    // add the new step to the list of steps, not the template itself 
    $scope.item.steps.push(newStep); 
};