Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Intercept and extend controller $scope

Tags:

angularjs

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?

like image 213
matsko Avatar asked Aug 14 '12 16:08

matsko


People also ask

What does $scope mean in AngularJS?

$scope is a child object that is used to bind the HTML(view) & Javascript(Controller) in a webpage. It is created with the ng-app directive. It is created with the ng-controller directive. It is available globally for all the controllers, i.e, the property assigned with “$rootscope” can be used anywhere.

Why $scope is used in AngularJS?

Scopes provide APIs ($apply) to propagate any model changes through the system into the view from outside of the "AngularJS realm" (controllers, services, AngularJS event handlers). Scopes can be nested to limit access to the properties of application components while providing access to shared model properties.

What is $scope used for in angular?

The $scope in an AngularJS is a built-in object, which contains application data and methods. You can create properties to a $scope object inside a controller function and assign a value or function to it. The $scope is glue between a controller and view (HTML).


1 Answers

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.

like image 64
Renan Tomal Fernandes Avatar answered Oct 24 '22 18:10

Renan Tomal Fernandes