0

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;
  }
}());
2
  • 3
    Add product service to Controller declaration ['$scope', -> ['$scope', 'productService', you are missing injector adnotation for productService Commented Feb 25, 2016 at 16:59
  • Related question (if not duplicate) with built-in $http service instead of custom service Commented Feb 25, 2016 at 17:01

1 Answer 1

2

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"];

}());
Sign up to request clarification or add additional context in comments.

2 Comments

This works although I am curious as to why it works and will continue looking
When you find out, let me know. This problem bugged me before as I believed order wasn't important in JS (or any functional program) but it must be to do with one of the Angular Elves.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.