【发布时间】:2015-02-24 18:31:03
【问题描述】:
我目前正在使用 Angular,但遇到了 $http 的问题。我的几个控制器使用 $http 只是文件,将结果应用到 $scope.variable 但是在我当前的控制器上我遇到了问题。
app.factory('getUserData', function($http) {
var user = [],
url = 'res/asp/manageaccount.asp?action=',
custid = getCookie('custid');
return {
getUserInfo: function() {
url += 'getUserInfo&custid=' + custid;
return $http.get(url);
},
getShipInfo: function(callback) {
url += 'getShipInfo&custid=' + custid;
return $http.get(url).then(function(response) {
user = response.data;
return user;
});
}
};
});
app.controller('accountController', ['$scope', 'getUserData',
function($scope, getUserData) {
$scope.custid = getCookie('custid');
getUserData.getUserInfo().then(function(data) {
$scope.userInfo = data.data;
console.log($scope.userInfo); // Logs the array with the object data I need
});
// Accessing $scope.userInfo here is 'undefined'
}
]);
我尝试了两种不同的方式来返回数据。数据返回正常,但我无法在我的页面中访问它 - 只能在定义 $scope.userInfo 的范围内。获取数据不是在页面上显示数据的问题。
<div class="container" ng-controller="accountController">
<h1>Welcome Back, {{userInfo.fname}}!</h1> <!-- Doesn't work -->
<div class="row" ng-controller="cartController">
<!-- This works fine -->
</div>
<div class="row">
{{userInfo.fname}} <!-- Doesn't work -->
{{custID}} <!-- Works -->
</div>
</div>
TL;DR
$http 返回数据,但无法在我的页面中使用{{userInfo.fname}} 访问它。
我看过很多 SO 问题/答案,而这个似乎是最多的relevant。
【问题讨论】:
-
console.log(data);输出什么? -
@Ronnie
Object {data: Array[1], status: 200, headers: function, config: Object, statusText: "OK"}和data.data输出[Object]其中包含我需要的数据。 -
好像是一个数组,如果你尝试访问
{{obj[0].prop}}呢?或scope.userInfo = data.data[0] -
console.log(data[0]); 做什么输出?
-
{{obj.prop}}只是一个占位符。我实际上是在使用{{userInfo.fname}}来尝试写出页面。记录$scope.userInfo会正确返回对象,但只能在getUserData.getUserInfo()声明内完成。
标签: javascript angularjs