如何从angularjs HTTP回调查看JSON数据? [英] How to view json data from angularjs http callback?
本文介绍了如何从angularjs HTTP回调查看JSON数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以在控制台中看到我的JSON数据,我想clickbutton功能后进行查看HTML页面上。从我understaning我可以做一个承诺($ Q)或然后通过HTTP或ngResource。首先,我想要做的HTTP然后再迁移到ngResource。出于某种原因,我的范围仍然是不确定的。也许这是一个NG-init或NG-重复我失踪?任何想法?
VAR应用= angular.module('对myApp',[]); app.factory('httpq',函数($ HTTP,$ Q){
返回{
得到:函数(){
变种推迟= $ q.defer();
$ http.get.apply(NULL,参数)
.success(deferred.resolve)
.error(deferred.resolve);
返回deferred.promise;
}
}
}); app.controller('myController的',函数($范围,httpq){ httpq.get(的http://本地主机:8080 /国)
。然后(功能(数据){
$ scope.returnedData =数据;
}) $ scope.clickButton =功能(){
$ scope.returnedData;
}});
查看
< DIV数据-NG-控制器=myController的>
<按键数据-NG-点击=clickButton()>获取数据从服务器16; /按钮>
< P> JSON数据:{{returnedData}}< / P> < / DIV>
解决方案
使用Ajax调用
块引用>服务
VAR demoService = angular.module('demoService',[])
。服务('为myService',['$ HTTP',函数($ HTTP){ this.getdata =功能(实体){
VAR承诺= $ HTTP({
方法:POST,
网址:服务/实体/加',
数据:实体,
标题:{
内容类型:应用/ JSON
},
缓存:假的
})。然后(功能(响应){
返回响应;
});
返回的承诺;
};
}]);
控制器:
VAR demoService = angular.module('demoService',[])
.controller('myctr',['$范围,为myService',函数($范围,为myService){
myService.getdata()。然后(功能(响应){
//成功 },函数(响应){ //错误
});}]);
现在你可以看到你的JSON控制器中的成功
I can see my json data in the console and I want to view it on html page after clickbutton function. From my understaning I can either do a promise ($q) or then with http or ngResource. First I want to do http then migrate to ngResource. For some reason my scope is still undefined. Maybe it's a ng-init or ng-repeat I'm missing? Any ideas?
var app = angular.module('myApp', []); app.factory('httpq', function($http, $q) { return { get: function() { var deferred = $q.defer(); $http.get.apply(null, arguments) .success(deferred.resolve) .error(deferred.resolve); return deferred.promise; } } }); app.controller('myController', function($scope, httpq) { httpq.get('http://localhost:8080/states') .then(function(data) { $scope.returnedData = data; }) $scope.clickButton = function() { $scope.returnedData; } });
view
<div data-ng-controller="myController"> <button data-ng-click="clickButton()">Get Data From Server</button> <p>JSON Data : {{returnedData}}</p> </div>
解决方案Use Ajax call
Service:
var demoService = angular.module('demoService', []) .service('myService',['$http', function($http) { this.getdata = function(entity){ var promise = $http({ method : 'POST', url : 'services/entity/add', data : entity, headers : { 'Content-Type' : 'application/json' }, cache : false }).then(function (response) { return response; }); return promise; }; }]);
Controller :
var demoService = angular.module('demoService', []) .controller('myctr',['$scope','myService',function($scope,myService){ myService.getdata().then(function(response){ //Success },function(response){ //Error }); }]);
now you can see your json in controller success
这篇关于如何从angularjs HTTP回调查看JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文