Can someone provide a use case for the $controller service in AngularJS?

mia picture mia · Jan 9, 2015 · Viewed 11k times · Source

Angularjs docs give the usage of $controller service as: $controller(constructor, locals);

Can anyone focus some light on these 2 points:

  1. When to use $controller service. Please provide some use case.
  2. Details about 'locals' parameter passed to it.

Answer

Shripal Soni picture Shripal Soni · Jan 9, 2015

You can create common functions which are to be executed on $scope into one controller may be named 'CommonCtrl'.

angular.module('app',[]).controller('CommonCtrl', ['$scope', function($scope){
      var self = this;
      $scope.stuff1 = function(){

      }

      $scope.stuff2 = function(){

      }
      self.doCommonStuff = function(){
               // common stuff here
               $scope.stuff1();
               $scope.stuff2();

      };
      return self;
}]);

And inject this controller in other controllers let say 'TestCtrl1' like

angular.module('app',[]).controller('TestCtrl1', ['$scope','$controller', function($scope, $controller){
        var commonCtrl = $controller('CommonCtrl',{$scope: $scope}); // passing current scope to commmon controller
        commonCtrl.doCommonStuff();
}]);

Here, the in second argument of $controller service, we are passing dependencies that are required by CommonCtrl. So the doCommonStuff method will use TestCtrl1 controller's scope.