在ng-repeat中添加和删除json列表

时间:2013-10-30 09:54:04

标签: javascript json angularjs

我想创建一个页面,其中有人向联系人添加了一个或多个位置,现在我有一些看起来像这样的内容。

<div class="input-append" ng-repeat="location in newPartner.partner_location">
    <input class="input-large" type="text" ng-model="location">
    <button class="btn" type="button" ng-click="delLocation1({{$index}})">- {{$index}}</button>
</div>

<div class="input-append">
    <input class="input-large" type="text" ng-model="new_location">
    <button class="btn btn-primary" type="button" ng-click="addLocation1()">+</button>
</div>

这是HTML,控制器看起来像这样。

$scope.newPartner = {'partner_name':'newname','partner_location':['X','Y','Z']};

$scope.addLocation1 = function() {
    $scope.newPartner.partner_location.push($scope.new_location);
    $scope.new_location = "";
}
$scope.delLocation1 = function(id) {
    $scope.newPartner.partner_location.splice(id, 1);
}

现在它在开始时工作得很好但是如果我删除一些项目并添加一些突然错误并开始删除前一项而不是我按下 - (减号)。

我做错了吗?提前谢谢你,丹尼尔!

1 个答案:

答案 0 :(得分:1)

首先从{{}}删除ng-click="delLocation1({{$index}})"。它应该是:

ng-click="delLocation1($index).

其次,我建议您添加一些基本调试器,以便在添加新值时查看模型会发生什么:<pre>{{newPartner.partner_location|json}}</pre>

第三,我会将模型更改为:

$scope.newPartner = {
        'partner_name': 'newname',
        'partner_location': [{value:'X'}, {value:'Y'}, {value:'Z'}]
    };

因为,通过这种方式:['X','Y','Z']我们无法修改我们的数据。

演示 Fiddle

最后这是我们的固定代码:

<强> HTML

<div ng-controller="fessCntrl">
    <div  ng-repeat="location in newPartner.partner_location">
        <input class="input-large" type="text" ng-model="location.value">
        <button class="btn" type="button" ng-click="delLocation1(newPartner.partner_location, $index)">{{$index}}</button>
    </div>
    <div class="input-append">
        <input class="input-large" type="text" ng-model="new_location">
        <button class="btn btn-primary" type="button" ng-click="addLocation1()">+</button>
    </div>        
        <pre>{{newPartner.partner_location|json}}</pre>
</div>

<强> JS

var fessmodule = angular.module('myModule', []);

fessmodule.controller('fessCntrl', function ($scope) {

    $scope.new_location = "empty";

    $scope.newPartner = {
        'partner_name': 'newname',
        'partner_location': [{value:'X'}, {value:'Y'}, {value:'Z'}]
    };

    $scope.addLocation1 = function () {
        $scope.newPartner.partner_location.push({value:$scope.new_location});
        $scope.new_location = "empty";
    }
    $scope.delLocation1 = function (locations, index) {
        locations.splice(index, 1);
    }
});

fessmodule.$inject = ['$scope'];