ng-repeat with empty objects

余生长醉 提交于 2019-12-02 13:53:17

问题


I'm getting a 'Duplicates in repeater' error. I read somewhere that I can track by index, but as soon as I do that all my object title and description values become duplicated. I need to define unique titles, descriptions and asset arrays for each individual step. How can I do this?

    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:


It's because you're adding the same object instance (stepTemplate) to the array each time. Angular sees that the array has multiple entries, but all of them point to the same object instance.

The solution here is to create copies of your template, and add the copies to the array, not the template itself. You can create deep copies using 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);
};


来源:https://stackoverflow.com/questions/30813862/ng-repeat-with-empty-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!