簡體   English   中英

如何在angular js中創建服務?

[英]How to create service in angular js?

這是我在angular.js中使用service的代碼。如果我運行此代碼,則會收到此錯誤Uncaught Error:[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>

demo.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> 

您在控制器定義中缺少$ scope服務名稱:

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

請記住,如果將服務名稱指定為參數的字符串,則必須指定函數的所有參數。 當您要縮小javascript時,建議指定用於注入的服務名稱。

考慮到這一點,可以對服務定義中的$ http參數執行相同的操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM