服务无法在简单的控制器中运行

service is not working in a simple controller

我有这个js代码

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

在我的 html 我有这个 .... ... 嗨{{fromService}} .... ... 控制台中没有错误,页面只是空白。

请查看 AngularJs 文档 "Using Dependency Injection"。

正确的做法:

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

您没有正确注入您的服务。

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

        $scope.fromService = testService.sayHello("World");

        $scope.toService = testService.sayGoodbye("World");

}]);

另外,在您的 HTML 中,您应该添加 ng-app="app"ng-controller 来指定您的控制器。

<!DOCTYPE html>
<html ng-app="app">
    <head></head>
    <body ng-controller="AboutCtrl">
        <p>Hi {{fromService}}</p>

     <!-- Also place here your JS files.-->>
    </body>
</html>

超级简单,实际上你是在注入服务错误的地方检查这个:

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

您可以通过这些方式将您的服务注入控制器。

行内数组注释

app.controller('MyController', ['$scope', 'testService', function($scope, testService) {
  // ...Code here
}]);

$注入属性注解

var MyController = function($scope, testService) {
  // ...
}
MyController.$inject = ['$scope', 'testService'];
app.controller('MyController', MyController);

隐式注释

app.controller('MyController', function($scope, testService) {
  // ...
});

如果您想知道哪一个是首选,请阅读这篇文章Dependency Injection