Troy Bryant
Troy Bryant

Reputation: 1024

Angularjs service undefined

Was building out an angular application, but am getting error undefined with the service or factory. Specifically "can not read property of setName undefined". I have went here to figure out my error. Even changed around my syntax figuring I maybe had something out of place but still throwing an undefined error.

Here is the controller:

(function() {
  "use strict";
  angular
    .module("app", [])
    .controller("mainCtrl", ["$scope", mainCtrl]);

  function mainCtrl($scope, productService) {

    $scope.testService = productService.setName("Data Service");
  }
}());

Here is the service script:

(function() {
  "use strict";
  angular
    .module("app")
    .service("productService", function() {

      var serviceObj = {};
      serviceObj.name = '';
      serviceObj.setName = function(newName) {
        serviceObj.name = newName;
      };
      return serviceObj;
    });
}());

Originally, I had the service as :

(function() {
  "use strict";
  angular
    .module("app")
    .service("productService", setName);

  function setName(newName) {
    var serviceObj = {};
    serviceObj.name = '';
    serviceObj.setName = function(newName) {
      serviceObj.name = newName;
    };
    return serviceObj;
  }
}());

Upvotes: 0

Views: 1557

Answers (1)

Dean Meehan
Dean Meehan

Reputation: 2647

I've had this problem recently and it seems to be that the function must be defined before the controller is created. I would recommend doing it the following way:

(function () {
"use strict";

//function
function mainCtrl($scope, productService) {
    $scope.testService = productService.setName("Data Service");
} 

//Controller and Module Init
angular
    .module("app", [])        
    .controller("mainCtrl", mainCtrl);  

//Inject requirements (This is needed for Minification) 
mainCtrl.$inject = ["$scope", "productService"];

}());

Upvotes: 2

Related Questions