这是我的指示
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());
}
}
});
当我尝试在浏览器上运行此功能时,我会在console
日志
categories:
[$promise: Object, $resolved: false]
categoryListing.js:25
getting parent categories categoryListing.js:19
allParentCategories: []
我很确定这不应该是空的。
问题
async
调用的性质被解雇了吗?由于
更新
Category
资源看起来像
angular.module('categoryService', ['ngResource']).factory('Category', function($resource) {
return $resource('categories/:categoryId', {categoryId: '@uuid'});
});
答案 0 :(得分:3)
(因为答案确实在评论中标记为社区维基)
这可能有助于您理解处理$resource
返回的承诺的方法:
var allParentCategories = function () {
console.log('getting parent categories');
var ret = [];
getCategories.then(function(results){
ret = _.uniq(results.data, function (category) {
console.log('category:', category);
return category.parent;
});
});
return ret;
};
我知道它不仅仅是直接从_.uniq
返回结果,但这就是当前JS状态的生命!