1

how can i access a function of one controller from another controller.

Here are two controllers, monthlyOptionsController and yearlyController.

myapp.controller("monthlyOptionsController", ['$scope','$injector', function($scope){

    $scope.initializeMonthlyCell   =   function(monthh){
    }
}]);

myapp.controller("yearlyController", ['$scope','$injector', function($scope){

    $scope.yearlyFunc   =   function(monthh){
         //here i want to access initializeMonthlyCell function 
         // like this initializeMonthlyCell(monthNumber);
    }
}]);

In yearlyFunc function i want to access initializeMonthlyCell function/ how can i do this. may be this repeat question.but anyone tell me how i can do this??

codef0rmer
  • 10,284
  • 9
  • 53
  • 76
Proxy_Server
  • 401
  • 1
  • 7
  • 17

2 Answers2

3

There are 2 approaches:

  • Create your initializeMonthlyCell in a service and inject it into your controllers to reuse.

  • Use $on, $emit, $broadcast to communicate between controllers scopes.

Example code with the first approach (it's more recommended in your case)

myapp.factory("dateService",function(){
       return {
             initializeMonthlyCell : function (month){

            }
        };
    });

    myapp.controller("monthlyOptionsController", ['dateService','$scope','$injector', function(dateService,$scope){

        $scope.initializeMonthlyCell   =   function(month){
           return dateService.initializeMonthlyCell(month);
        }
    }]);

    myapp.controller("yearlyController", ['dateService','$scope','$injector', function(dateService,$scope){

        $scope.yearlyFunc   =   function(monthh){
             // call dateService.initializeMonthlyCell
        }
    }]);
Khanh TO
  • 48,509
  • 13
  • 99
  • 115
  • Khanh TO can you explain with my code.because i am new in angularJS – Proxy_Server Dec 28 '13 at 05:25
  • 1
    @priyashivale: I updated my answer. The second approach is another way to communicate between scopes. It's possible but not recommended in your case because you have to communicate back the result to `yearlyController` (unnecesarily complex). I did not include a code for it. – Khanh TO Dec 28 '13 at 05:47
1

I think the best way to write a service to be injected in both controllers in order to share data.

myapp.service('Monthly', function() {
   return {
      initializeMonthlyCell: function(month) {
         return month;
      }
   }
});

myapp.controller("monthlyOptionsController", function($scope) { 

});

myapp.controller("yearlyController", function($scope, Monthly) {
   $scope.yearlyFunc   =   function(monthh){
     return Monthly.initializeMonthlyCell(monthh);
   }
});
Rubyist
  • 6,486
  • 10
  • 51
  • 86
codef0rmer
  • 10,284
  • 9
  • 53
  • 76