2016-11-11 26 views
-1

想从HTTP请求获取返回的对象到另一个对象的范围,所以我可以在HTML与ng-repeat指令使用它。我怎样才能得到返回的对象到一个变量?

  1. 调用HTTP功能
  2. 获取数据
  3. 存储响应
  4. 使范围变量HTTP响应的

JS值:

angular.module('myApp').controller('ItemController',[ 
    '$scope', '$http', '$location', 
    function($scope, $http, $location){ 

    var currentLocation = $location.path(); 

    $scope.getItem = function(){ 
     $http.get('path/to/json/file.json').then(
     function(response){ 
      $scope.results = response.data; 
      console.log('item controller, item:', $scope.results); 
     }); 

    }; 

    $scope.item = //MAKE THIS VALUE OF THE RETURN OBJECT FROM getItem 
     console.log('scope.item', $scope.item); 
    } 
]); 

JSON

[ 
    { 
    "first_name": "Mega", 
    "last_name": "Man", 
    "image": "http://placehold.it/75x75" 
    } 
] 

HTML

想能够只是

<p>{{item.first_name}}</p> 
<p>{{item.last_name}}</p> 
<img ng-src="{{item.image}}"/> 

更新JS调用

$scope.getItem = function(){ 
    $http.get('path/to/json/file.json') 
    .success(function(data){ 
     $scope.results=data; 
     console.log('$scope.results: ',$scope.results); 
    }).error(function(data){ 
     console.log(data); 
    }).then(
     function(){ 
     $scope.item = $scope.results; 
     console.log('$scope.item: ', $scope.results); 
     }); 
    }; 
+0

你所要求的是类似于派人去接你比萨饼,然后希望它是什么在他们离开车道之前在桌上。你必须在回调中设置'$ scope.item'。 –

+0

确定如此更新了JS调用,并使用'.tccess()'方法的初始调用从'.then()'方法获取数据。现在日期在那里,它如何暴露于HTML? –

+0

就像你拥有iirc一样。尽管.then和$ scope.results是多余的。我怀疑“数据”并不完全像你认为的那样。 –

回答

0

你Ç在以不同的方式做到这一点的方法之一是使用successerror回调功能,如:

$http.get('path/to/json/file.json') 
       .success(function (data, status, header, config) { 
        $scope.results =data; 
      console.log('item controller, item:', $scope.results); 
       }) 
       .error(function (data, status, header, config) { 
        console.log(data); 
       }); 

另一种选择是使用then承诺功能,如:

$http({method: 'GET', url: 'path/to/json/file.json'). 
     then(function(response) { 
      $scope.results = response.data; 
      console.log('item controller, item:', $scope.results); 
     }, function(response) { 
      console.log(response); 
     }); 
+0

感谢您的回应,但即使改变了通话方式,我仍然坚持不懈。我需要能够在HTML中说出“{{item.name}}”等。我唯一能做的就是通过你的例子调用整个对象'{{results}}'并返回一个完整的JSON对象。我需要能够调用诸如“{{results.name}}”或“{{results.image}}”的具体信息。 –

+0

刚刚对我的问题进行了编辑,希望现在对预期结果更清楚一点。再一次感谢你的帮助。 –

0

问题的一切?什么让回调正常工作。更换.then().success().error()。由于被调用的对象是一个数组,因此无法在HTML中解析该对象以获取对象属性。需要的是,另一部分是在成功回调以获取数组的第一个对象,具有$scope.results=data[0]

$scope.getItem = function(){ 
    $http.get('path/to/json/file.json') 
    .success(function(data){ 
    $scope.results=data[0]; 
    console.log('$scope.results: ',$scope.results); 
    }).error(function(data){ 
    console.log(data); 
    }); 
}; 
+0

请添加一些关于此代码如何回答问题的解释。这将有助于提供未来观众可以从中学习的答案。有关更多信息,请参阅[答案]。 –

+0

感谢提醒,增加了清晰度 –