gpt4 book ai didi

javascript - 如何在 Angular JS 中创建服务?

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

这是我在 angular.js 中使用服务的代码。如果我运行此代码我收到此错误未捕获错误:[ng:areq]。

</ons-toolbar>
<div ng-controller="testAppController">
Search: <input ng-model="query" type="text" class="text-input" id="my-input"/>
<table>
<tr>
<th>Country</th>
<th>Population</th>
</tr>
<tr ng-repeat="country in countries | filter:query">
<td>{{country.name}}</td>
<td>{{country.population}}</td>
</tr>
</table>
</div>

<div ng-include='"partials/footer.html"'></div>
</ons-page>

演示.js

angular.module('testsapp',[])
.service('helloworldservice',function($http){
this.getDatafunction = function(){
$http.get('json/countries.json')
.success(function(data) {
alert("sucesss");
})
.error(function(data) {
alert("wrong");
});
}
})
.controller('testAppController',['helloworldservice',function($scope,helloworldservice){
helloworldservice.getDatafunction();
}]);

最佳答案

这里

 .controller('testAppController',['helloworldservice',function($scope,helloworldservice)

您需要更改为

.controller('testAppController',['$scope','helloworldservice',function($scope,helloworldservice)

请在此处阅读更多内容

https://docs.angularjs.org/tutorial/step_05#a-note-on-minification

angular.module('testsapp', []).service('helloworldservice', function($http) {
this.getDatafunction = function() {
$http.get('json/countries.json').
success(function(data) {
alert("sucesss");
}).
error(function(data) {
alert("wrong");
});
}

}).controller('testAppController', ['$scope','helloworldservice',
function($scope, helloworldservice) {

helloworldservice.getDatafunction();
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="testsapp">

<div ng-controller="testAppController">
Search: <input ng-model="query" type="text" class="text-input" id="my-input"/>
<table>
<tr>
<th>Country</th>
<th>Population</th>
</tr>
<tr ng-repeat="country in countries | filter:query">
<td>{{country.name}}</td>
<td>{{country.population}}</td>
</tr>
</table>
</div>

<div ng-include='"partials/footer.html"'></div>

</body>

关于javascript - 如何在 Angular JS 中创建服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26882541/

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