0

I am trying to create an angular service but it is not working. I have tried numeros things and looked all over.Please help

 //service 

 angular
    .module('RDash')
    .factory('googleLogin', googleLogin); 

function googleLogin() 
{
    this.testFunc = function () 
    {
        console.log("THIS IS A TEST SERVICE");
    }
};

Below: tryoing to call service test func

//controller

angular
    .module('RDash')
    .controller('ComposeCtrl', ['$scope','$rootScope','$http','googleLogin', ComposeCtrl]);

function ComposeCtrl($scope, $rootScope, $http, googleLogin) {
    console.log("ComposeCTRL active");

    googleLogin.testFunc(); // this doesnt work, error: "main.min.js:2 Error: [$injector:undef] http://errors.angularjs.org/1.5.8/$injector/undef?p0=googleLogin" 

I feel like the issue is with injecting i just dont know where. Please help thanks

Daniel Corzo
  • 1,055
  • 2
  • 19
  • 32
Lauren L
  • 11
  • 2

1 Answers1

3

Factory needs to return the function refrence and you need to declare variable testFunc (answer to why here):

Update working snippet.

angular.module('RDash', []);
angular
  .module('RDash')
  .factory('googleLogin', googleLogin);

function googleLogin() {
  var testFunc = function() {
    console.log("THIS IS A TEST SERVICE");
  }
  return {
    testFunc : testFunc
  }
};

angular
  .module('RDash')
  .controller('ComposeCtrl', ['$scope', '$rootScope', '$http', 'googleLogin', ComposeCtrl]);

function ComposeCtrl($scope, $rootScope, $http, googleLogin) {
  console.log("ComposeCTRL active");

  googleLogin.testFunc();
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="RDash" ng-controller="ComposeCtrl"></div>

angular
   .module('RDash')
   .factory('googleLogin', googleLogin);

 function googleLogin() {

   var testFunc = function() {
     console.log("THIS IS A TEST SERVICE");
   }

   return {
     testFunc: testFunc
   }

 };
Community
  • 1
  • 1
Ajay Narain Mathur
  • 5,326
  • 2
  • 20
  • 32