4

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?

1
  • You can avoid this using ng-if, with removes completely the element and scope Commented Sep 19, 2016 at 12:04

2 Answers 2

9

create new scope and destroy it like:

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

//later
newScope.$destroy();
Sign up to request clarification or add additional context in comments.

Comments

1

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.