Here is my directive
angular.module('categoryListingDirective', []).directive('categoryListing', function (Category) {
return {
restrict: 'A',
replace: true,
require: true,
scope: true,
templateUrl: '../static/partials/categoryListingForm.html',
link: function (scope, element, attrs) {
var categories = undefined;
var getCategories = function () {
if (categories === undefined) {
categories = Category.query(function(){});
}
return categories;
};
var allParentCategories = function () {
console.log('getting parent categories');
return _.uniq(getCategories(), function (category) {
console.log('category:', category);
return category.parent;
});
};
console.log('categories:', getCategories());
console.log('allParentCategories:', allParentCategories());
}
}
});
When I try to run this on my browser, I see the following in console log
categories:
[$promise: Object, $resolved: false]
categoryListing.js:25
getting parent categories categoryListing.js:19
allParentCategories: []
I am pretty sure this should not be empty.
Question
- Is it because of
asyncnature of calls getting fired? - How do I fix it, what are the recommendations?
Thanks
UPDATE
The Category resource looks like
angular.module('categoryService', ['ngResource']).factory('Category', function($resource) {
return $resource('categories/:categoryId', {categoryId: '@uuid'});
});
Categoryresource? At a glance,Categoryis returning a promise that you need to resolve in your $http success callback. When you callgetCategories()you'll be able to callgetCategories().then(function(data) { ... })may want to read about deferred objects ala docs.angularjs.org/api/ng/service/$qquerycall is asynchronous. I think the syntax might be counter-intuitive as pointed out in this question stackoverflow.com/questions/11966252/…