$success call back function from AngularJS

前端 未结 3 1997
傲寒
傲寒 2020-12-21 15:49

I am calling the controller to get the API value. How do I pass the array outside of the $http method?

I need to pass an array, pa[], to the $scope

3条回答
  •  离开以前
    2020-12-21 16:45

    This code is asynchronous. pa is assigned to $scope.myData before the $http service has had a chance to get the value from your API call.

    You need to use the $q service promise library to control the flow of your code. Something like this:

    function Ctrl($scope, $http, $q) {
      var url = "https://spreadsheets.google.com/feeds/list/0AsXjbsnPIu06dGswZUV4WX/values?alt=json-in-script&callback=angular.callbacks._0";
      var pa = [];
      var paPromise = $q.defer()
    
      $http({
        method: 'JSONP',
        url: url
      }).success(function(data) {
    
          for (i = 0; i < data.feed.entry.length; i++) {
            var entry = data.feed.entry[i];
            pa.push(entry.gsx$productivity.$t);
            console.log(pa); //[10,20,30,40,50]
          }
          paPromise.resolve(pa)
        });
    
      $scope.myData = paPromise.promise;
    }
    

    Here, we inject the $q service and instantiate a variable paPromise using it. Next, we give this promise to $scope.myData. Once the promise gets resolved inside the $http success method, AngularJS will notify your $scope and update the value and it'll be reflected on your template/DOM.

提交回复
热议问题