如果从javascript中删除元素,如何在angularjs中手动销毁范围?

时间:2016-09-19 10:58:22

标签: javascript angularjs angularjs-scope

我将角度模板插入元素。 请考虑以下示例,

<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();
            }]);
        } 
    });
}

当我点击标签渲染功能时,每次都会调用。 还有其他任何吸烟吗?

2 个答案:

答案 0 :(得分:6)

创建新范围并将其销毁:

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

//later
newScope.$destroy();

答案 1 :(得分:1)

你可以使用

$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

类似的问题在这里 Provide an example of scope's $destroy event?