ZurabWeb
ZurabWeb

Reputation: 1368

How to properly delete the directive scope from controller in AngularJS 1.2

I'm trying to remove an instance of a directive from the page with a controller call and getting some kind of digest issue that I can't seem to be able to figure out. Looks like the scope isn't getting cleaned up properly and evens are still fired after the element is removed. Help is appreciated.

Here's my trimmed down HTML:

<div ng-controller="MyCtrl">
  <div class="directive-text" ng-style="style('green')" my-directive>This is my directive</div>
  <a ng-click="delete()">[ delete ]</a>
</div>

And my JS:

var demo = angular.module('demo', []);

demo.directive('myDirective', function() {
  return {
    link: function($scope, $element) {
      console.log('init directive');
    }
  }
});

demo.controller("MyCtrl", ['$scope', '$compile', function($scope, $compile) {
 $scope.items = {
    'red': {
      style: {
        color: 'red'
      }
    },
    'green': {
      style: {
        color: 'green'
      }
    }
  };

  $scope.style = function(color) {
    return $scope.items[color].style;
  }

  $scope.delete = function() {
    console.log('deleting...');
    $('.directive-text').remove();
    delete $scope.items['green'];
  };
}]);

Here's a plunker: http://plnkr.co/edit/Rfp93aTucdivy0zguJaF

Upvotes: 1

Views: 2066

Answers (1)

Florian Lim
Florian Lim

Reputation: 5362

Searching on SO for "angular remove directive from DOM" got me this: Angularjs remove custom directive and child directives from DOM

The short version: You should destroy the scope of the directive before you remove it from the DOM.

$scope.delete = function() {
  console.log('deleting...');
  // Destroy the directive's scope
  angular.element(document.querySelector(".directive-text")).scope().$destroy();
  // I changed the following line to avoid using jQuery
  angular.element(document.querySelector(".directive-text")).remove();
  delete $scope.items['green'];
};

Upvotes: 1

Related Questions