Van*_*idi 5 angularjs angularjs-scope angular-http
我试图使用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
});
Run Code Online (Sandbox Code Playgroud)
HTML:
<section ng-controller="booksCtrl">
<h2 ng-repeat="book in data">{{book.name}}</h2>
</section>
Run Code Online (Sandbox Code Playgroud)
Don*_*nal 16
您应该将$ http.get放在控制器中.
此外,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;
});
});Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
48984 次 |
| 最近记录: |