Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
855 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...