2

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']);
5
  • You can use $rootScope Commented Nov 20, 2016 at 16:36
  • 1
    ... or consider using a service, if you wan't to share logic between controllers. Commented Nov 20, 2016 at 16:37
  • @JyothiBabuAraja $rootScope not working Commented Nov 20, 2016 at 16:38
  • It seems like you're trying to use your controllers as a class that other controllers inherit from. Instead, have your controllers require dependencies from services (like generic functions/classmethods) Commented Nov 20, 2016 at 16:47
  • This feels like an XY problem. You have some unknown problem, and your attempted solution is to have one module call a function in a different module. Not only does this break quite a few design principles (Open/Close, Single Responsibility, Dependency Inversion, etc.), it also doesn't make for a very clear question. Commented Nov 20, 2016 at 16:50

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The 'home' module depends on a service defined in the module named 'yourModule'. The dependency needs to be included: angular.module('home', ['yourService']).controller....
Yes, if 'yourModule' is a new module it should be registered like angular.module('yourModule', [/*dependencies*/]), and should be included as angular.module('home',['yourModule']), or he could inject it into myApp to make it available for every other module.
0

This is not the good practice, but fulfills your need.

You can access functions over controllers using $rootScope.

Read more from here

Home Controller:

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

Another Controller:

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

1 Comment

while this would actually work, there are numerous reasons that this kind of practice should be avoided.
0

You can do it in two ways:

1. Creating and Using AngularJS Service:

Here is an complete example of how to create an AngularJS Service and use the AngularJS Service Mehtod in different Controllers:

//AngularJS Module

var app = angular.module("Demo", ["ngRoute"])

//AngularJS Route Config

app.config(function($routeProvider, $locationProvider) {
    $routeProvider.caseInsensitiveMatch = true;
    $routeProvider.when("/products/details/:id",
    {
        templateUrl: "Temaplates/details.html",
        controller: "productDetailsController"
    })
     .when("/products/edit/:id",
    {
        templateUrl: "Temaplates/edit.html",
        controller: "productEditController"
    })

// AngularJS Service

app.factory('productService', function ($http, $routeParams) {
      return {
          getDataById: function () {
              //return promise from here
              return $http.get("http://localhost:43618/api/Products", {
                  params: { id: $routeParams.id }
              });
          }
      };
  });

// AngularJS Controllers Where Service Method has been used

app.controller("productDetailsController", function ($scope, $http, $routeParams, $location, productService) {
     $scope.message = "Product Details";
     productService.getDataById().then(function (response) {
         $scope.product = response.data;
     }, function (error) {
         console.log("Error occured ", error);
     });
});

.controller("productEditController", function ($scope, $http, $routeParams, $location, productService) {
    $scope.message = "Edit Page";
    $scope.product = {};

    productService.getDataById().then(function (response) {
        $scope.product = response.data;
    }, function (error) {
        console.log("Error occured ", error);
    });

   $scope.updateProduct = function (product) {
        $http({
            method: "PUT",
            url: "http://localhost:43618/api/Products",
            params: { id: $routeParams.id },
            data: product
        })
        .success(function () {
            alert("Product Updated Successfully");
            $location.path('/products');
        });
    }

})

2. Using rootScope Object

But There is a problem using rootScope object and that is: Whenever you refresh your page rootScope object will be lost.

So it always better to use AngularJS Service over rootScope

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.