简体   繁体   中英

array.splice shows strange behavior in Angular Js directive

Checkout this plunkr
http://plnkr.co/edit/FQ7m6HPGRrJ80bYpH8JB?p=preview

In that After adding element when I delete element from array using splice method.
Everything gets messed up.

code

Array.splice needs an array index. The problem with your code is that you are passing the ngModel.index to the removeNode function and splicing an array with that index which is not actual array index.

You need to find the correct element index by looping through it and by checking its index property of each element. As I'm doing angular.forEach which seconds parameter gives us actual index of that array.

Code

    $scope.removeNode = function(index) {
      var foundIndex;
      angular.forEach($scope.sitemap, function(value, idx){
        if(value.index === index)
        foundIndex = idx;
      })

      $scope.sitemap.splice(foundIndex, 1);

    }

Demo Plunkr

When you create an object you hardcode the index of each new added object with you value of "abc"

var abc = 0;
$scope.addNode = function(){
    abc++;
    var addObj = {name:"name"+abc, index:abc};
    $scope.sitemap.push(angular.copy(addObj));
}

Then when you removing and calling function with this hardcoded value of index

$scope.removeNode = function(index){
    $scope.sitemap.splice(index,1);                     
}

So for example let say you have this array:

obj1 - hardcoded index 0 - array index 0
obj2 - hardcoded index 1 - array index 1

if remove obj1 from array with index 0 your obj2 will have index 0 in the array then,

obj2 - hardcoded index 1 - array index 0

but in your case you still passing to the removeNode function index 1 as it was created with that value.

I suggest another solution for that: Demo

In my opinion:

  • sitemap should not define in current directive( sample ), because, it is list item(not list).

  • Also, there is addNode method in your controller. there, removeNode should be declared.

You can access controller's method in directive through removeAction: '&removeAction', :

scope: {
    ngModel: "=ngModel",//or "="
    removeAction: '&removeAction',//or "&"
  },
  controller: ["$scope", function($scope) {
    $scope.removeNode = function(item) {
      $scope.removeAction({
        item: item
      });
    }
  }],

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