AngularJS Intercept and extend controller $scope

All we need is an easy explanation of the problem, so here it is.

There is a lot of reusable functionality that I have defined in my application that EVERY controller uses with the $scope variable. Instead of me having to create a shared service each time, is there a way to extend the $scope variable so that I can have my extended code available everywhere?

Something like:

//I've tested this out and it doesn't work, but this is what I want to do.
angular.module('App',[]).config(['$scopeProvider',function($scope) {
  $scope.method1 = function() { ... };
  $scope.method2 = function() { ... };
}]);

Then later on:

var HomeCtrl = function($scope) {
  $scope.method1();
};

Is this possible? Or do I need to create a shared service and then have the $scope extend from that for the first line of each controller?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Instead of .config try .run, this will do exactly what you want.

angular.module('App', []).run(['$rootScope', function($rootScope) {
  $rootScope.foo = function() {
     alert("WIN!");
  };
}]);

angular.module('App').controller('HomeCtr', ['$scope', function($scope) {
  $scope.foo(); #will call the alert
}]);

NOTE I have only used module.controller because I like it, var HomeCtrl = function($scope) { will have the same effect.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply