rekna rekna - 5 months ago 50
AngularJS Question

angularjs controllerAs register $destroy

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 ?

Answer

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.

Comments