ng-repeat与空对象 [英] ng-repeat with empty objects

查看:105
本文介绍了ng-repeat与空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到在转发器中重复"错误.我读了一些可以按索引跟踪的地方,但是一旦这样做,我所有的对象标题和描述值就会重复.我需要为每个步骤定义唯一的标题,描述和资产数组.我怎样才能做到这一点?

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> 

推荐答案

这是因为您每次都将相同的对象实例(stepTemplate)添加到数组中. Angular看到数组有多个条目,但是它们都指向同一个对象实例.

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.

这里的解决方案是创建模板的副本,然后将副本添加到数组中,而不是模板本身.您可以使用 angular.copy() 创建深拷贝.

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);
};

这篇关于ng-repeat与空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆