Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs controllerAs register $destroy

Tags:

angularjs

Documentation of angular says, to execute code to cleanup when the controller is destroyed, one should register for the $destroy event on the scope.

$scope.$on("$destroy", function() { ... } );

However, when you use the controllerAs syntax, you don't have access to $scope. How would you register the $destroy event ?

like image 357
rekna Avatar asked Jul 31 '14 08:07

rekna


People also ask

How to register Component in AngularJS?

Components can be registered using the . component() method of an AngularJS module (returned by angular. module() ).

How to set rootScope in AngularJS?

module('myApp'). controller('myCtrl', function($scope) { var a = //something in the scope //put it in the root scope }); angular. module('myApp'). controller('myCtrl2', function($scope) { var b = //get var a from root scope somehow //use var b });

How to add new Component in AngularJS?

To create a component, we use the . component() method of an AngularJS module. We must provide the name of the component and the Component Definition Object (CDO for short).

What is oninit in AngularJS?

OnInitlinkA lifecycle hook that is called after Angular has initialized all data-bound properties of a directive.


2 Answers

Just because you use the controllerAs syntax, it doesn't mean there is no $scope or that you can't use it.

In fact, all the controllerAs does is add the controller's this on the $scope (under the specified name). E.g.:

ng-controller="SomeCtrl as ctrl"

will implicitly do this:

.controller('SomeCtrl', function () {
    this.value = 'something';
    ...

    // Angular will implicitly so something equivalent to:
    // $scope.ctrl = this;
}

So, there is nothing stopping you from using the $scope (it is actually quite useful for things like $watching stuff and sending/listening for events):

<!-- In the VIEW -->
<div ng-controller="SomeCtrl as ctrl">
    Some value: {{ctrl.value}}
    <button ng-click="ctrl.doSomething()">Some action</button>
</div>

/* In the CONTROLLER */
.controller('SomeCtrl', function ($scope) {
    this.value = 'some value';
    this.doSomething = function () { ... };

    $scope.$on('$destroy', function () {
        // So some clean-up...
    });
});

See, also, this short demo.

like image 129
gkalpak Avatar answered Sep 19 '22 05:09

gkalpak


It is also possible without injecting $scope:

.controller('SomeCtrl', function () {
    var vm = this;
    vm.$onDestroy = function(){
        console.log( 'destroying....' );
    }   
}
like image 44
frulo Avatar answered Sep 22 '22 05:09

frulo