Skip to content

Instantly share code, notes, and snippets.

@preslavrachev
Last active August 29, 2015 14:16
Show Gist options
  • Save preslavrachev/cb1743e9cf063d0ad8c2 to your computer and use it in GitHub Desktop.
Save preslavrachev/cb1743e9cf063d0ad8c2 to your computer and use it in GitHub Desktop.
This gist provides a simple and clean way to override the the default initialization of all Angular JS controllers, by using a decorator
<body data-ng-app="myApp">
<div ng-controller="myController">{{data}}</div>
</body>
// declare the app
var app = angular.module("myApp", []);
app.config(['$provide', function($provide) {
$provide.decorator('$controller', ['$delegate', function($delegate) {
return function(constructor, locals) {
//All the code the you put here will execute BEFORE the actual
//initialization of the controller
//using locals, you can access and modify the scope, via locals.$scope
console.log("Executing the overriding code...");
//This particular example returns the same constructor expression,
//but you can return a completely new one, if you like:
//https://docs.angularjs.org/api/ng/service/$controller#usage
return $delegate(constructor, locals);
}
}]);
}]);
app.controller("myController", ['$scope', function($scope) {
console.log("myController initialized!");
$scope.data = "Test data";
}])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment