Reputation: 971
I am inserting angular template to element. Consider following example,
<p>
<c ng-controller="ctrl">
...
</c>
</p>
if I remove c from javascript. What will be side effects? (scope leaks) How to avoid this?
I have used this,
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();
}]);
}
});
}
when I click tab render function get called everytime. Any other sugestions?
Upvotes: 4
Views: 16112
Reputation: 1408
you can use
$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;
}
it is awlays good practice to define your scope variable as object like
$scope.currentControllerscope ={}
$scope.currentControllerscope.myVar1 ="string"
$scope.currentControllerscope.myVar2 ="string2"
so that you can destryo whole object like
delete $scope.currentControllerscope
Similar question is here Provide an example of scope's $destroy event?
Upvotes: 1
Reputation: 1577
create new scope and destroy it like:
var newScope = $rootScope.$new(true);
$compile(template)(newScope);
//later
newScope.$destroy();
Upvotes: 9