Lauren L Lauren L - 13 days ago 5
AngularJS Question

Simple angular service not working

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

A.J A.J
Answer

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
   }

 };