简体   繁体   中英

Angularjs splice array of objects inside of an object always removes last object

I have an object which contains an array of objects called "blocks":

$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: []
};

When I add stuff to this array, it behaves perfectly normally:

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

However when I try to remove an object from the array by calling this function on ng-click and passing in the object from an 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);
}

I am able to get both the correct object and the correct index in my console, but when it goes to splice the array, the last object is always being deleted which is very strange as this should only be happening when the index I'm trying to delete doesn't exist (and therefore would equal -1)

Any ideas why this could be happening?

EDIT: I have also tried using ng-click="microsite.blocks.splice($index, 1)" directly in the element, as well as passing the $index into the function instead of the element. In all cases, the correct index is found, but the result is still the same, only the last entry is ever deleted.

Turns out this was an error with "track by $index" in Angular. After removing "track by $index" from my ng-repeat, splice() functioned normally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM