gpt4 book ai didi

javascript - 从 dom 中删除指令后使用 $scope.$destroy()

转载 作者:行者123 更新时间:2023-11-28 19:08:41 26 4
gpt4 key购买 nike

我有一个用 ng-if 条件切换的指令。该指令使用 jqlite 函数在 DOM 上添加元素(例如一些动画)。

但即使该指令不存在于 DOM 中,也会触发添加动画的 jqlite 函数。

我认为使用 ng-if 删除指令是不够的,但它的范围也需要删除。

somepage.html - 已编辑

<directivename class="classname1" ng-if="condition">
</directivename>

指令.js

return{
controller:function($scope,$element,$rootScope){
/*adding and removing elemnts to dom */
}
}

我到底应该如何使用 $scope.$destroy() ?

当我看到 $element 变量的值时,它有以下内容

$$hashKey: "object:336"
accessKey: ""
attributes: NamedNodeMap
baseURI: ""
childElementCount: 1
childNodes: NodeList[3]
children: HTMLCollection[1]
classList: DOMTokenList[3]
0: "classname1"
1: "ng-scope"
2: "ng-isolate-scope"
length: 3

The classname1 refers to the classname I gave to directive. But that directive is not present in DOM. Still the $element.classList contains that classname.

这与 $scope.$destroy() 问题有关吗?

最佳答案

What $destroy() do ?

The order of operations in your AngularJS directive is important because of the way jQuery implements the .remove() method. When you remove an element from the DOM using .remove() or .empty(), jQuery will clear out the event bindings and the data associated with the element so as to avoid memory leaks. This means that if you remove the element before you trigger the "$destroy" event, the element will be in a "sanitized state" by the time your $destroy event handler is executed.

在你的指令中,你应该这样调用它

ctrl.directive('directivename', function() {
return function(scope, element, attributes) {
scope.$on('$destroy', function() {
//Code to be execute just before destroying this directive or broadcast any mesage
});
};
});

关于javascript - 从 dom 中删除指令后使用 $scope.$destroy(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31152729/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com