ng-repeat 与空对象

2023-12-15

我收到“中继器重复”错误。我在某处读到可以通过索引进行跟踪,但是一旦我这样做,我的所有对象标题和描述值就会变得重复。我需要为每个步骤定义唯一的标题、描述和资产数组。我怎样才能做到这一点?

    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> 

这是因为您要添加相同的对象实例(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);
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ng-repeat 与空对象 的相关文章

随机推荐