angularjs - 使用 Angular.js 从 Web 服务获取数据

标签 angularjs angularjs-scope angular-http

我试图使用 Angular 从远程 WS 获取 Json 格式的数据,但遇到了一些问题。
数据正确来自 Web 服务,但我无法在 Controller 内部使用它。
这是为什么?
Angular 代码:

var booksJson;
var app = angular.module('booksInventoryApp',[]);

// get data from the WS
app.run(function ($http) {
    $http.get("https://SOME_API_PATH").success(function (data) {
        booksJson = data;
        console.log(data);  //Working
    });
});

app.controller('booksCtrl', function ($scope) { 
    $scope.data = booksJson;
    console.log($scope.data); //NOT WORKING
});

HTML:
<section ng-controller="booksCtrl">
<h2 ng-repeat="book in data">{{book.name}}</h2>
</section>

最佳答案

你应该把你的 $http.get 放在你的 Controller 中。

此外,Web 服务返回一个对象而不是数组。所以你的 ng-repeat 应该是这样的:book in data.books
这是一个工作示例:

var app = angular.module('booksInventoryApp', []);

app.controller('booksCtrl', function($scope, $http) {

  $http.get("https://whispering-woodland-9020.herokuapp.com/getAllBooks")
    .then(function(response) {
      $scope.data = response.data;
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<article ng-app="booksInventoryApp">
  <section ng-controller="booksCtrl">
    <h2 ng-repeat="book in data.books">{{book.name}}</h2>    
  </section>
</article>

关于angularjs - 使用 Angular.js 从 Web 服务获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30625002/

相关文章:

javascript - AppComponent.html :1 ERROR Error: No provider for Http! 在注入(inject)错误(core.es5.js:1169)

javascript - 如何处理调用同一函数的多个 Ajax 调用?

javascript - $http.put 可以将数据写入 JSON 文件吗

javascript - 安装 angular-google-maps 时出现问题

html - 使用完全分离的前端和用户身份验证

angularjs - 以 Angular 将对象转换为json

javascript - AngularJs 模板中的 $scope 变量快捷方式

javascript - 如何在加载时从 ng-view 的 Controller 触发函数—— Angular

javascript - Angular 仅发送模型的更改字段或复制更改后的模型

javascript - 使用 `this.$watch` 而不是 `$scope.$watch` 和 'Controller As'