从Angular.js Web服务获取数据 [英] Getting data from a web service with Angular.js
本文介绍了从Angular.js Web服务获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试着去使用一些麻烦角和IM远程WS获得一个JSON格式的数据。
该数据来自Web服务正常,但我不能用它在控制器内部。
这是为什么?
角code:
VAR booksJson;
VAR应用= angular.module('booksInventoryApp',[]);//从WS数据
app.run(函数($ HTTP){
$ http.get(https://开头SOME_API_PATH).success(功能(数据){
booksJson =数据;
的console.log(数据); //加工
});
});app.controller('booksCtrl',函数($范围){
$ scope.data = booksJson;
的console.log($ scope.data); //不工作
});
HTML
<节NG控制器=booksCtrl>
< H2 NG重复=书数据> {{book.name}}< / H>
< /节>
解决方案
您应该把你的$ http.get控制器内。
而且,Web服务返回对象不是阵列。所以,你的NG-重复应该是这样的:书data.books
下面是一个工作的例子:
\r
\r\r
\r VAR应用= angular.module('booksInventoryApp',[]);\r
\r
app.controller('booksCtrl',函数($范围,$ HTTP){\r
\r
$ http.get(https://whispering-woodland-9020.herokuapp.com/getAllBooks)\r
。然后(功能(响应){\r
$ scope.data = response.data;\r
});\r
});
\r
&LT;脚本SRC =https://ajax.googleapis.com/ajax /libs/angularjs/1.2.23/angular.min.js\"></script>\r
&lt;物品NG-应用=booksInventoryApp&GT;\r
&lt;节NG控制器=booksCtrl&GT;\r
&LT; H2 NG重复=书data.books&GT; {{book.name}}&LT; / H&GT;\r
&LT; /节&gt;\r
&LT; /条&GT;
\r
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>
解决方案
You should put your $http.get inside your controller.
Also, the web service returns an object not an array. So your ng-repeat should be something like this: book in data.books
Here is a working example:
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屋!
查看全文