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??

0

2 Answers 2

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
        }
    }]);
Sign up to request clarification or add additional context in comments.

2 Comments

Khanh TO can you explain with my code.because i am new in angularJS
@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.
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);
   }
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.