Search code examples
angularjsangularjs-serviceangularjs-controller

Angular service can not be found


I am trying to set up a simple service example for myself in angular and I am having trouble. The service should return Hello World then the controller should log it to the console.

The error is saying:

[$injector:modulerr] Failed to instantiate module ColorService due to: Error: [$injector:nomod] Module 'ColorService' is not available!

What am I doing wrong here.

Service.js

var Service = angular.module('Service', []);

Service.service('Service', function() {
  function test(){
    return 'Hello World'
  }
}

Main.js

angular.module('iukapp', ['Service']).controller('MainCtrl', MainCtrl);

MainCtrl.$inject = ['$scope', 'Service'];

function MainCtrl($scope, Service){
  console.log(Service.test());
}

Solution

  • You need to assign your function to context of your service (this) and then it will be accessible: this.test = function() {return "Hello world";};