我试图使用 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/