Search code examples
angularjsangularjs-service

AngularJS not binding promise to template


My service:


This was mistake 1 of 2 cause of my error:

        getAll: function(url) {
         deferred.resolve($http({  <--- deferred.resolve should not have been here
                method: 'GET',
                url: url,
                contentType: "application/json; charset=utf-8",
                cache: true,
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }                    
            }));
            return deferred.promise;
        },

Should have been instead:

        getAll: function (url) {
            $http({
                method: 'GET',
                url: url,
                contentType: "application/json; charset=utf-8",
                cache: true,
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            }).success(function (data) {
                deferred.resolve(data);
            });
            return deferred.promise;

My controller:

This was mistake 2 of 2 cause of my error:

     // $scope.PassengerVehicles = crudSvc.getAll('/_json/PassengerVehicles.js');
     // should have been:
      crudSvc.getAll('/_json/PassengerVehicles.js').then(function (data) {
        $scope.PassengerVehicles = data;
    });

My template:

       <ul data-ng-repeat="passVeh in PassengerVehicles">
          <li>{{passVeh.itemId}}</li>
        </ul>

Here is my plunker, which has been corrected:

AngularJS not binding promise to template

Than You Fourth!!


Solution

  • You have the getAll() function immediatly resolving and returning a promise to the controller. You need to allow the getAll() function to execute and deal with the promise when that resolves:

    getAll: function(url) {
                return $http({
                    method: 'GET',
                    url: url,
                    contentType: "application/json; charset=utf-8",
                    cache: true,
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }                    
                });
            },
    

    and in the controller:

        crudSvc.getAll('/_json/PassengerVehicles.js').success(function (vehicles){
            $scope.PassengerVehicles = vehicles;
          });
    

    The difference is that you are returning a promise that immediately resolves and returns another promise. You only need to resolve the http promise.