Search code examples
javascriptangularjsangularjs-serviceangularjs-factory

Angularjs - Inject factory without reference


I have the following code:

main.js

angular.controller('myCtrl', function($scope, $rootScope) {
    $scope.name = "Bob";
}

myservices.js

angular.factory('myService', function($http) {

  var myService = {
    async: function(params) {
      // $http returns a promise, which has a then function, which also returns a promise
      var promise = $http.get("http://myws/user/info/"+params).then(function (response) {
        // The then function here is an opportunity to modify the response
        console.log(response);
        // The return value gets picked up by the then in the controller.
        return response.data;
      });
      // Return the promise to the controller
      return promise;
    }
  };
  return myService;
});

How can inject myService in myCtrl ? considering they are in two separated files.


Solution

  • We need to add in order all of our scripts we have created to run this angular, take note the order:

    <script src="angular.js"></script>
    <script src="main.js"></script>
    <script src="myservices.js"></script>
    

    main.js should look like:

    var app = angular.module("MyModule", []);
    app.controller('myCtrl', function($scope, $rootScope, myService) { /* implementation */})
    

    services.js should look like:

    app.factory('myService', function($http) { /* implementation */});
    

    So in our main.js we are creating a module to attach all of our services, factories, providers, values, constants, controllers and directives. It also allows us to put the config and run phase functions in.

    The module is instantiated via:

    angular.module("MyModule", []);

    We're providing a second argument of other dependant modules

    If we needed to, we could ask angular for the module again, in the case of use javascript modules:

    var app = angular.module("MyModule");