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?
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.
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With