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

标签 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>

演示.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/

相关文章:

angularjs - 如何从 transclude 函数访问 transclusion 槽?

javascript - AngularJS ui-router - 设置菜单处于事件状态

javascript - 如何在 vue.js 中动态设置@click?

c++ - BOOST ASIO POST HTTP REQUEST——标题和正文

java - Json 结构如此不同,无法将其更改为 Java 对象

json - 如何从字典数组中按键选择数据?

html - 绝对定位的内容不会显示在 angular ui-router ui-view 中

javascript - 解析 JSON 数据并打印

javascript - 未捕获的类型错误 : Cannot read property 'click' of null

javascript - pnotify 拒绝工作