Noor
Noor

Reputation: 20150

Removing Directive using Isolated Scopes

I'm having several directives in a container where I need to be able to remove each of them specifically. Each directive is in a big a div which contains a remove button as well.

The controller:

app.controller('eventController', function($scope, $rootScope){;    
  $scope.removeEvent = function (id){
    console.log(id);
    $scope.$broadcast("$destroy" + id);
  }
});

The directive:

app.directive('eventView', function () {
  return {
    restrict: 'E',
    replace:true,
    templateUrl: 'partials/EventView.html',
    controller: 'eventController',
    scope: {id : '@'},
    link: function(scope, element){  
        scope.$on("$destroy"+scope.id,function() {
            element.remove();
        }); 
    }
  }
});

The issue is that I'm getting an error with this line scope.$on("$destroy"+scope.id,function() { saying that id is undefined

to add the directive:

app.controller('AddTimelineController', function($scope, $rootScope,$compile){
  $scope.id = 0;
  $scope.addEvent = function (){
    newElement = $compile("<event-View id=\"{{id}}\"></event-View>")($scope);
    $scope.id = $scope.id+1;
    eventContainer = angular.element(document.getElementById('eventContainer'));
    eventContainer.append(newElement);
  }
});

To remove the directive:

app.controller('eventController', function($scope, $rootScope){;    
  $scope.removeEvent = function (id){
    console.log(id);
    $scope.$broadcast("$destroy" + id);
  }
});

Upvotes: 1

Views: 268

Answers (1)

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

Instead using $broadcast I would use $watch into link that will listen on id change.

See Demo in Plunker

It's true that $watch() is doing dirt-checking vs $broadcast()and $broadcast() is cheaper than $watch().

However in your case you call the link before removeEvent is called and therefore directive doesn't see proper id you use.

Upvotes: 1

Related Questions