Last active
August 29, 2015 14:16
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<body data-ng-app="myApp"> | |
<div ng-controller="myController">{{data}}</div> | |
</body> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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