Matoy
Matoy

Reputation: 1818

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?

Upvotes: 1

Views: 1167

Answers (2)

dfsq
dfsq

Reputation: 193261

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) {...}.

Upvotes: 4

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22875

Most propbably you have not added service script in index.html

<script src="src/your_path/script.js" ></script>

Upvotes: 1

Related Questions