【问题标题】:Angular - $http Scope IssueAngular - $http 范围问题
【发布时间】: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


【解决方案1】:

我认为这就是您正在寻找的答案。您应该将 .then(data) 重命名为 .then(response) 以避免混淆。 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];
  });
}]);

【讨论】:

    猜你喜欢
    • 2013-09-26
    • 2016-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多