Super Hornet
Super Hornet

Reputation: 2907

remove button doesn't work

I'm going to add a custom angular directive which contains a button inside to delete itself.

My Problem is by clicking the button removeMe it is not able to delete an item from the array. Any idea what is wrong?

html:

<button type="button" data-ng-click="main.addNew()">Add new!</button>
<div id="container">
    <sample id="$index" list="main.list" data-ng-repeat="item in main.list"></sample>
</div>

directive template:

<div id="">
  <button type="button" ng-click="removeMe()">Remove Me</button>
</div>

js:

angular.module('TestApp', [])



.controller('MainController', function () {
    var main = this;
    main.list = [];
   main.addNew = function addNew() {
     main.list.push({id:'sdgsgs'});
   }
})

.directive('sample', function () {
  return {
    restrict: 'E',
    scope: {list: '=', id:'='},
    templateUrl: 'home.html',
    link: function (scope, element, attrs) {
      console.info(scope.list);
      console.info(scope.id);
      scope.removeMe = function removeMe() {
        scope.list.slice(scope.id, 1);
        console.info(scope.list);
      }
    },
    controller: function() {
        console.log("ctrl");
    }
  }
});

Upvotes: 0

Views: 50

Answers (1)

squiroid
squiroid

Reputation: 14027

Hey it's simple you are using slice instead of splice on array.

An important aspect of slice is that it does not change the array which invokes it

Use Splice instead of slice :)

scope.list.splice(scope.id, 1);

Plunker

Upvotes: 1

Related Questions