Muhammad Umar
Muhammad Umar

Reputation: 348

Provide factory of one module to another module

I have just started working on Angularjs and facing a problem in calling the factory defined in other module. Actually I need to clean the code so I have to build all the functionalities in one js file and I have to use them in my main js file where I have defined my controllers. I have made a simple code to understand the problem. Thanks in advance

Following is the Html file:-

<!DOCTYPE html>
<html>
  <head>
    <script data-require="[email protected]" data-semver="1.1.5"  src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="function.js"></script>
    <script src="script.js"></script>
  </head>
  <body ng-app="MyServiceModuleOne">
    <div ng-controller="TestController">
      <button type="button" ng-click="getFn()"> Test  </button>
    </div>
  </body>
</html>

Following is script.js file

var myModule= angular.module('MyServiceModuleTwo',['MyServiceModuleOne']);
myModule.controller('TestController', ['$scope', 'notify',    function($scope, notify){
  $scope.getFn = function() {
    notify.sampleFun();
  }
}]);

Following is function.js file:-

var myModule = angular.module('MyServiceModuleOne', []);
myModule.factory('notify',  function() {
  return {
    sampleFun: function() {
      alert('hi');
    }   
   };
});

Upvotes: 0

Views: 180

Answers (1)

Gangadhar Jannu
Gangadhar Jannu

Reputation: 4414

There are couple of changes needed. You are referencing MyServiceModuleOne as root module, but the controller you are referencing is in MyServiceModuleTwo.

So change your ng-app from MyServiceModuleOne to MyServiceModuleTwo.

I've updated the plnkr

Upvotes: 1

Related Questions