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

前端之家收集整理的这篇文章主要介绍了angularjs – 使用Angular.js从Web服务获取数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图使用Angular从远程WS获取Json格式的数据,我遇到了一些麻烦.
数据来自Web服务正确,但我不能在控制器内使用它.
这是为什么?
角度代码

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

此外,Web服务返回的对象不是数组.所以你的ng-repeat应该是这样的:在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相关文章