Indepnt dev Indepnt dev - 11 days ago 7
AngularJS Question

Is it possible to inject factory into service in AngularJs?

I have created some function in factory

App.factory('CustomHttpRequest', function ($http, $q) {
return {
ajaxRequest: function () {
return "test";
}
}
});


and I want to Access it in service like below

hhwtApp.service('listPlacesService', ['$rootScope', 'CustomHttpRequest', function($rootScope, CustomHttpRequest) {

this.listPlacesData = function () {

CustomHttpRequest.ajaxRequest();
}

}]);

Answer

yes you can use like below,your almost close......

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope,listPlacesService) {
  $scope.name = 'World';
  $scope.checking =listPlacesService.listPlacesData();
  console.log($scope.checking);
  
});

app.service('listPlacesService', [ 'CustomHttpRequest', function( CustomHttpRequest) {

     this.listPlacesData = function () {

            return CustomHttpRequest.ajaxRequest();
        }

    }]);
    app.factory('CustomHttpRequest', function () {
  
        return {
            ajaxRequest: function () {
                return "test";
            }
        }
    });
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{checking}} done!</p>
  </body>

</html>

check the console which will return "test" to your controller