Kaker Kaker - 1 year ago 83
Javascript Question

AngularJS how to use function from one controller in other controller

I create modular application in angularjs, I have two modules home and templates. how to use the functions of one module into the second module

Module Home

angular.module('home',[]).controller('homeCtrl', function($scope){
//this function to templatesModule
$scope.useThisFunctionInTemplateCtrl = function(){}

Module templates

angular.module('templates',[]).controller('templatesCtrl', function($scope){
//here function from homeCtrl
$scope.functionFromhomeCtrl = function(){}

Main app.js

angular.module('myApp',['home', 'templates']);

Answer Source

You need a service to share information between controllers:

angular.module('yourModule').factory('yourService', function(){
    var self = this;

    self.sharedFunction = function(){}

    return self;

And inject it in your controllers

angular.module('home',[]).controller('homeCtrl', function($scope, yourService){
     //this function to templatesModule
     $scope.useThisFunctionInTemplateCtrl = yourService.sharedFunction();

$rootScope is for storing global variables, it should be avoided otherwise.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download