gpt4 book ai didi

javascript - Angular js : put service in other file

转载 作者:行者123 更新时间:2023-12-03 10:22:11 25 4
gpt4 key购买 nike

我试图将我的服务文件放入另一个 js 文件中,但出现错误

Unknown provider: $scopeProvider <- $scope <- getData

我创建了 3 个文件,它们是:

app.js

app=angular.module('myApp', []); console.log("app.js loaded.");

service.js

app.service('getData',['$scope','$http',function($scope,$http){
this.getDataFrom = function(){
$http.get("http://www.w3schools.com/angular/customers.php")
.success(function(response) {$scope.names = response.records;});
}; }]); console.log("script loaded.");

index.html

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js"></script><script src="app.js"></script><script src="service.js"></script>

<script>app.controller('customersCtrl',['$scope','getData', function($scope, getData) {
alert(getData.getDataFrom());}]);</script>

基本上我想把 this代码在不同的文件中。

最佳答案

您无法将范围注入(inject)到服务中。它不会那样工作,因为它们不与范围关联。

尝试按如下方式重写代码:

去掉服务和注入(inject)中的$scope引用,并返回$http.get的结果,这是一个promise

app.service('getData',['$http',function($http){
this.getDataFrom = function(){
return $http.get("http://www.w3schools.com/angular/customers.php")
}; }]); console.log("script loaded.");

然后,更改 Controller 以使用该服务,并在获取数据时更新其范围:

<script>app.controller('customersCtrl',['$scope','getData','commentDataService', function($scope, getData,commentDataService) {
commentDataService.getComments().then(function(data) {
$scope.data = data;
console.log('the data is here!', data);
});
alert(commentDataService.getComments());
alert(getData.getDataFrom());}]);</script>

关于javascript - Angular js : put service in other file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29575869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com