服务不适用于简单的控制器

时间:2016-06-18 01:52:54

标签: angularjs angularjs-directive angularjs-scope angularjs-service

我有这个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}}      .... ... 控制台中没有错误,页面只是空白。

4 个答案:

答案 0 :(得分:5)

请查看AngularJs文档“使用依赖注入”。

正确的方法:

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

答案 1 :(得分:2)

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

内联数组注释

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

$ inject属性注释

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

隐式注释

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

如果您想知道哪一个是首选,请阅读此Dependency Injection

答案 2 :(得分:1)

您没有正确注入服务。

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>

答案 3 :(得分:1)

晚餐容易,其实你是服务错误的地方检查这个:

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