想从HTTP请求获取返回的对象到另一个对象的范围,所以我可以在HTML与ng-repeat
指令使用它。我怎样才能得到返回的对象到一个变量?
- 调用HTTP功能
- 获取数据
- 存储响应
- 使范围变量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);
});
};
你所要求的是类似于派人去接你比萨饼,然后希望它是什么在他们离开车道之前在桌上。你必须在回调中设置'$ scope.item'。 –
确定如此更新了JS调用,并使用'.tccess()'方法的初始调用从'.then()'方法获取数据。现在日期在那里,它如何暴露于HTML? –
就像你拥有iirc一样。尽管.then和$ scope.results是多余的。我怀疑“数据”并不完全像你认为的那样。 –