I have a simple app and couple of controllers. In each controller I defined a "init" function. I do this because I want that it can be easy to "refresh" the controller - just call the init function like this: $scope.init().
In other words, something like Page_Load event in .Net (A function that if you defined it in your code it will be firing when the page is load.
I'm trying to use decorator function that run for each controller, but I don't know how to finish this to accomplish the mission.
var myApp = angular.module('myApp',[]);
myApp.decorator('$controller', ['$delegate', function ($delegate) {
return function (constructor, locals) {
var controller = $delegate.apply(null, arguments);
// Never got hear
if (locals.$scope && locals.$scope.init) {
console.log('init');
locals.$scope.init();
}
return angular.extend(function () {
return controller();
}, controller);
};
}]);
myApp.controller('ctrl1', function($scope) {
$scope.init = function() {
$scope.name = 'Superhero';
};
// I don't want to call this
$scope.init();
});
myApp.controller('ctrl2', function($scope) {
$scope.init = function() {
$scope.name = 'Mario';
};
// I don't want to call this
$scope.init();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="myApp">
<div ng-controller="ctrl1">
Hello, {{name}}!
</div>
<div ng-controller="ctrl2">
My name is, {{name}}!
</div>
</div>