Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does AngularJs automatically destroy scope when an element is removed from a directive?

Say I have directive:

angular.module('myApp').directive('myDirective', function ($compile) {
    return {
        link: function ($scope, $element, $attrs) {
            var $randomElem = $('<div>');
            $element.append($compile($randomElem)($scope));

            $randomElem.remove();
        }
    }
});

Will the scope be automatically destroyed? If not, how can I destroy it?

like image 541
Jeff Avatar asked Feb 10 '16 17:02

Jeff


People also ask

What is scope in AngularJS directive?

Scope in a Directive Well, all of the directives have a scope associated with them. This scope object is used for accessing the variables and functions defined in the AngularJS controllers, and the controller and link functions of the directive.

What is isolate scope in AngularJS?

Isolated scope directive is a scope that does not inherit from the parent and exist on its own. Scenario: Lets create a very simple directive which will show the object from the parent controller.

What does $compile do in AngularJS?

Overview. Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together. The compilation is a process of walking the DOM tree and matching DOM elements to directives. Note: This document is an in-depth reference of all directive options.

Which directive initializes an AngularJS application?

The ng-app directive initializes an AngularJS application. The ng-init directive initializes application data. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.


1 Answers

In your case your $randomElem will have the same scope as its parent (the directive container). So it won't be destroyed.

Now it you were to create a new scope for this element:

// Case 1: child scope sharing the properties with parent
$element.append($compile($randomElem)($scope.$new()));

// case 2: child scope isolated, no sharing with parent
$element.append($compile($randomElem)($scope.$new(true)));

Then you would need to manually destroy the scope when removing the element. For tha you can use $scope.$destroy()

For instance:

var newScope = $scope.$new();
$element.append($compile($randomElem)(newScope));


newScope.$destroy(); // or $randomElem.scope().$destroy();
$randomElem.remove();
like image 180
floribon Avatar answered Oct 30 '22 20:10

floribon