-1

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

+0

你有没有在你的HTML中的任何地方放置一个'ng-app'声明? – Makoto

+0

在app.controller('AboutCtrl',['testService',function($ scope,$ location,$ http){'line。')中添加'testService'作为依赖项。 –

回答

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

你没有正确注射服务。

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到especify控制器。

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

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

晚餐容易,其实您注射服务错误的地方进行检查:

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

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

嵌入式阵列注释

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

相关问题