AngularJS:函数inside指令不返回数据

时间:2014-05-16 05:37:07

标签: javascript angularjs

这是我的指示

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'});
});

1 个答案:

答案 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状态的生命!