-1

I'm trying to make a basic data pulling using a service and print it on screen when I have data, but something is not working.

My service:

mymodule.factory('MyService', function($http, $q) {
    var service = {
        getData: function() {
            var dfd = $q.defer();
            $http.get(apiServerPath).success(function (data) {
                dfd.resolve(data);
            });
            return dfd.promise;
        }
    }

    return service
}

My Controller:

mymodule.controller('myCtrl', ['$scope', 'MyService', function($scope, MyService) {
     $scope.myvar = MyService.getData();
}

HTML

<div> {{myvar}} </div>

What I can see from the browser console -

  1. The myvar object turn into a promise object
  2. The success function is being called and 'data' has valid data in it
  3. And for my question and issue - the controller's variable does not change when the defer object is resolving - why?
Ben Diamant
  • 6,186
  • 4
  • 35
  • 50

1 Answers1

5

Promises are no longer auto-unwrapped as of Angular 1.2. In your controller do the following:

mymodule.controller('myCtrl', ['$scope', 'MyService', function($scope, MyService) {
     MyService.getData().then(function success(data) {
       $scope.myvar = data;
     });
}
rtucker88
  • 986
  • 8
  • 15