Wild Beard
Wild Beard

Reputation: 2927

Angular - $http Scope Issue

I'm currently working with Angular and have an issue with $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.

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. 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>

TL;DR

$http returns data but cannot access it with {{userInfo.fname}} in my page. I've looked a lot of SO questions/answers and this one seems to be the most relevant.

Upvotes: 0

Views: 96

Answers (1)

Ronnie
Ronnie

Reputation: 11198

I think this is the answer you are looking for. You should rename .then(data) to .then(response) to avoid confusion. response.data[0] should be the object

app.controller('accountController', ['$scope', 'getUserData', function($scope, getUserData)
{
  $scope.custid = getCookie('custid');
  getUserData.getUserInfo().then(function(response)
  {
    $scope.userInfo = response.data[0];
  });
}]);

Upvotes: 1

Related Questions