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 ?
Components can be registered using the . component() method of an AngularJS module (returned by angular. module() ).
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 });
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).
OnInitlinkA lifecycle hook that is called after Angular has initialized all data-bound properties of a directive.
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 $watch
ing 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.
It is also possible without injecting $scope:
.controller('SomeCtrl', function () {
var vm = this;
vm.$onDestroy = function(){
console.log( 'destroying....' );
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With