我试图使用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应该是这样的:book in data.books
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>