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>
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.
$q. defer() allows you to create a promise object which you might want to return to the function that called your login function.
$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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With