Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 731
ram1993 Avatar asked Oct 23 '25 21:10

ram1993


2 Answers

create new scope and destroy it like:

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

//later
newScope.$destroy();
like image 115
Valery Kozlov Avatar answered Oct 25 '25 11:10

Valery Kozlov


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?

like image 44
Vicky Kumar Avatar answered Oct 25 '25 13:10

Vicky Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!