[英]Angular - $http Scope Issue
I'm currently working with Angular and have an issue with $http
. 我目前正在使用Angular并在
$http
遇到问题。 A couple of my controllers use $http
just file, applying the results to $scope.variable
however on my current controller I'm having an issue. 我的几个控制器使用
$http
just文件,将结果应用于$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'
}
]);
I've tried two different ways to return the data. 我尝试了两种不同的方法来返回数据。 The data returns fine however I cannot access it in my page - only within the scope of defining
$scope.userInfo
. 数据返回正常,但是我无法在页面中访问它-仅在定义
$scope.userInfo
的范围内。 Getting the data isn't the issue it is displaying it on the page. 获取数据并不是它显示在页面上的问题。
<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>
$http
returns data but cannot access it with {{userInfo.fname}}
in my page. $http
返回了数据,但是无法使用页面中的{{userInfo.fname}}
进行访问。 I've looked a lot of SO questions/answers and this one seems to be the most relevant . 我看过很多SO问题/答案,而这似乎是最相关的 。
I think this is the answer you are looking for. 我认为这是您正在寻找的答案。 You should rename
.then(data)
to .then(response)
to avoid confusion. 您应该将
.then(data)
重命名为.then(response)
以避免造成混淆。 response.data[0]
should be the object response.data[0]
应该是对象
app.controller('accountController', ['$scope', 'getUserData', function($scope, getUserData)
{
$scope.custid = getCookie('custid');
getUserData.getUserInfo().then(function(response)
{
$scope.userInfo = response.data[0];
});
}]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.