Search code examples
angularjsangularjs-directiveangularjs-scopeangularjs-service

service is not working in a simple controller


I have this js code

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


app.service('testService', function(){
  this.sayHello= function(text){
    return "Service says \"Hello " + text + "\"";
  };
  this.sayGoodbye = function(text){
    return "Service says \"Goodbye " + text + "\"";
  };
});


app.controller('AboutCtrl', ['testService', function ($scope, $location, $http) {


  $scope.fromService = testService.sayHello("World");
  $scope.toService = testService.sayGoodbye("World");
}]);

and in my html I have this .... ... hi {{fromService}} .... ... There are no errors in console and the page is just blank.


Solution

  • Please take a look at AngularJs Docs "Using Dependency Injection".

    The correct way:

    app.controller('AboutCtrl', ['$scope', '$location', '$http', 
    'testService', function ($scope, $location, $http, testService) {
            $scope.fromService = testService.sayHello("World");
            $scope.toService = testService.sayGoodbye("World");
    }]);