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

Say I have a 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 area be automatically destroyed? If not, how can I destroy it?

+4
source share
1 answer

In your case, yours $randomElemwill have the same scope as its parent (directive container). Therefore, it will not be destroyed.

Now you had to create a new area 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 need to manually destroy the area when you delete the item. For this you can use$scope.$destroy()

For example:

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


newScope.$destroy(); // or $randomElem.scope().$destroy();
$randomElem.remove();
+7
source

Source: https://habr.com/ru/post/1628175/


All Articles