【问题标题】:Angularjs splice array of objects inside of an object always removes last objectAngularjs拼接对象内部的对象数组总是删除最后一个对象
【发布时间】:2016-05-07 14:24:40
【问题描述】:

我有一个对象,其中包含一个名为“块”的对象数组:

$scope.microsite = {
    images: [
        {url: "https://unsplash.it/800/400/?image=20"},
        {url: "https://unsplash.it/800/400/?image=15"},
        {url: "https://unsplash.it/800/400/?image=52"}
    ],
    blocks: []
};

当我向这个数组添加东西时,它表现得非常正常:

$scope.addElement = function(a){
    if(a=='heroslider'){
        var data = {
            slides: [
                {
                    id:0,
                    image:0,
                    title: "Title",
                    desc: "Description",
                },
                {
                    id:1,
                    image:1,
                    title: "Title",
                    desc: "Description",
                },
                {
                    id:2,
                    image:2,
                    title: "Title",
                    desc: "Description",
                }
            ]
        };
    } else if(a=='threecol'){
        var data = {
            columns: [
                {
                    title: "Column one",
                    text: "This is a column for features",
                },
                {
                    title: "Column two",
                    text: "This is a column for features",
                }
            ]
        };
    }
    var element = {
        template: a,
        data: data
    };
    $scope.microsite.blocks.push(element);
}

但是,当我尝试通过在 ng-click 上调用此函数并从 ng-repeat 传入对象来从数组中删除对象时...

$scope.removeElement = function(element){
    var x = $scope.microsite.blocks.indexOf(element);
    console.log($scope.microsite.blocks[x]);
    console.log(x);
    $scope.microsite.blocks.splice(x, 1);
}

我能够在我的控制台中获得正确的对象和正确的索引,但是当它拼接数组时,最后一个对象总是被删除,这很奇怪,因为这应该只在索引我的时候发生'正在尝试删除的内容不存在(因此等于 -1)

任何想法为什么会发生这种情况?

编辑: 我也尝试过直接在元素中使用 ng-click="microsite.blocks.splice($index, 1)" 以及将 $index 传递给函数的元素。在所有情况下,都找到了正确的索引,但结果仍然相同,只有最后一个条目被删除。

【问题讨论】:

    标签: javascript arrays angularjs splice


    【解决方案1】:

    原来这是 Angular 中“track by $index”的错误。从我的 ng-repeat 中删除“track by $index”后,splice() 正常运行。

    【讨论】:

      猜你喜欢
      • 2017-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-23
      • 1970-01-01
      相关资源
      最近更新 更多