Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a promise into ngRepeat

Tags:

angularjs

So, I saw an example where they were passing an angualar deferred into ngRepeat and it worked fine. For some reason when I set up this example it doesn't work. Can anyone tell me why? If you assign the data without the deferred it works fine i.e. $scope.objects = [{id:1}...]
Many thanks
Fiddle here

<!doctype html>
<html ng-app="app">
<head>
</head>
<body>

  <testlist/>

  <script src="/lib/angular/angular.js"></script>
  <script>
   var app = angular.module('app', []);

   app.factory('dataService', function ($q) {
     return {
       getData : function () {
         var deferred = $q.defer();
         setTimeout(function () {
           deferred.resolve([{id:1},{id:2},{id:3},{id:4}]);
         },0);
         return deferred.promise;
       }
     };
   });


   app.directive('testlist', ['dataService', function(dataService) {
     return {
        restrict: 'E',
        replace: true,
        scope : {},
        template: '<div ng-repeat="data in objects">{{inspect(data)}}{{data.id}}</div>',
        controller: function($scope) {
          $scope.objects = [{id:1},{id:2},{id:3},{id:4}];
          $scope.inspect = function (obj) {
            console.log(obj)
          }
        }
      }
    }]);

  </script>
</body>
</html>
like image 589
screenm0nkey Avatar asked Jan 24 '14 16:01

screenm0nkey


People also ask

How to use promise in AngularJS?

Example of a Promise // We create our promise $http. get('api/status') // that once complete will call either our success callback function // or our error callback function . then(function success(response) { // handle our response object $log. log(response); }, function error(response) { // handle our error $log.

What is q defer()?

$q. defer() allows you to create a promise object which you might want to return to the function that called your login function.

What is$ q in Angular?

$q is integrated with the $rootScope. Scope Scope model observation mechanism in AngularJS, which means faster propagation of resolution or rejection into your models and avoiding unnecessary browser repaints, which would result in flickering UI. Q has many more features than $q, but that comes at a cost of bytes.


1 Answers

I don't think you can use the promise objects directly, you should use the then callbacks as stated in the documentation.

This means that your

$scope.objects = dataService.getData();

Should instead be something like

dataService.getData().then(function(data) {
    $scope.objects = data;
});

Otherwise, your $scope.objects will contain the promise object, and not the data you are passing to resolve.

See the updated fiddle here.

like image 61
Raibaz Avatar answered Oct 20 '22 20:10

Raibaz