如何在角度js中创建服务?

时间:2014-11-12 08:38:49

标签: javascript json angularjs onsen-ui

这是我在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>

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();
  }]);

2 个答案:

答案 0 :(得分:1)

这里

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

答案 1 :(得分:0)

您缺少控制器定义中的$ scope服务名称:

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

请记住,如果将服务名称指定为参数的字符串,则必须指定该函数的所有参数。建议使用注入服务名称when you will minify the 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");
      });     
  }
}])