Matoy Matoy - 5 months ago 12
Javascript Question

why do I get "service is not defined" error message in angular page?

I have this code in a script.js file:

scotchApp.factory('myService', function() {
var savedData = {}
function set(data) {
savedData = data;
}
function get() {
return savedData;
}

return {
set: set,
get: get
}

});

scotchApp.controller('SharedController',['$scope', 'myService', function($scope) {
myService.set('hello');
$scope.message = myService.get();
}]);


when I try to upload an html that uses this code I get in chrome (F12 mode):
angular.js:12722 ReferenceError: myService is not defined

why?

Answer

You never injected your service into controller. Correct code:

scotchApp.controller('SharedController', ['$scope', 'myService', function($scope, myService) { 
  myService.set('hello');
  $scope.message = myService.get();
}]);

Note controller function signature function($scope, myService) {...}.

Comments