如果元素从javascript中移除,如何在angularjs中手动销毁作用域

How to destroy scope manually in angularjs if element is removed from javascript?

本文关键字:angularjs 作用域 元素 javascript 如果      更新时间:2023-09-26

我插入角模板元素。考虑下面的例子,

<p>
  <c ng-controller="ctrl">
    ...
  </c>
</p>

如果我从javascript中删除c。会有什么副作用?(范围泄漏)如何避免这种情况?

我用过这个,

function render() {
    var lastScope = angular.element('c').scope();
            
    if(lastScope) {
        lastScope.$destroy();
    }
    $('c').remove();
    getTemplate(context + '/c.html', function(template) {
        if (template) {
            angular.element(document).injector().invoke(['$compile', '$rootScope', function($compile, $rootScope) {
                $('p').append($compile(template)($rootScope));
                $rootScope.$apply();
            }]);
        } 
    });
}

当我点击标签渲染函数每次被调用。还有其他建议吗?

创建新的作用域并销毁它,如下:

var newScope = $rootScope.$new(true);
$compile(template)(newScope);
//later
newScope.$destroy();

可以使用

$scope.$on("$destroy",destroyScope);
$scope.destroyScope =function(){
// here you can delete your this function will be called whenever you move out from you controller here you can destroy you scope
 $('c').remove();
 delete $scope.var1;
}

将作用域变量定义为像

这样的对象总是好的做法。
$scope.currentControllerscope ={}
$scope.currentControllerscope.myVar1 ="string"
$scope.currentControllerscope.myVar2 ="string2"

这样你就可以像

那样销毁整个对象
delete $scope.currentControllerscope

这里也有类似的问题提供一个scope's $destroy event?