我将角度模板插入元素。 请考虑以下示例,
<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();
}]);
}
});
}
当我点击标签渲染功能时,每次都会调用。 还有其他任何吸烟吗?
答案 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