使用 Angular.js 从 Web 服务获取数据 [英] Getting data from a web service with Angular.js

查看:21
本文介绍了使用 Angular.js 从 Web 服务获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Im trying to get data in a Json format from a remote WS using Angular and im having some trouble. The data comes from the web service correctly but i cant use it inside the controller. Why is that? Angular Code:

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 放在你的控制器中.

You should put your $http.get inside your controller.

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

Also, the web service returns an object not an array. So your ng-repeat should be something like this: 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>

这篇关于使用 Angular.js 从 Web 服务获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆