Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
850 views
in Technique[技术] by (71.8m points)

javascript - How to view json data from angularjs http callback?

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...