javascript - 使用 $resource 和 $q 初始化 $scope 变量

标签 javascript angularjs angular-promise

我正在尝试使用从服务调用 resource.query() 的函数初始化 Angualr 作用域变量,并返回空值。

下面是我的代码

Controller

$scope.categories = _processedCategories($scope.excludedCategories);

// excluded categories is an array of objects
function _processedCategories(excludedCategories) {
    preDefinedCategoryService.rest.query({},
        function (data) {
            categories = _.filter(data._embedded.categories, function (n) {
                return (n.id !== excludedCategories.id);
            });    
            return categories
        },
        function () {
            console.log ('error');
        });    
   }

我的 $scope.categories 为空,但是当我 $scope.categories = _.filter(..) 时,它会直接填充它们。我知道它与 $promise 有关,但如何根据我的要求解决它?因为我以后也想重用这个函数。

最佳答案

您无法从异步操作返回。使用 Promise API 提供在加载和处理数据时调用的回调:

_processedCategories($scope.excludedCategories).$promise.then(function(categories) {
    $scope.categories = categories;
});

// excluded categories is an array of objects
function _processedCategories(excludedCategories) {
    return preDefinedCategoryService.rest.query({}, function (data) {
        return categories = _.filter(data._embedded.categories, function (n) {
            return (n.id !== excludedCategories.id);
        });
    }, function () {
        console.log('error');
    });
}

请注意,_processedCategories 现在返回 preDefinedCategoryService.rest.query 函数调用的结果,即 Promise 对象。

关于javascript - 使用 $resource 和 $q 初始化 $scope 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31219500/

相关文章:

javascript - Angular foreach 等待 http 调用的问题

javascript - ui-select 无结果事件

angularjs - 引用错误 : spyOn is not defined Angularjs/Karma/Jasmine

javascript - Firefox 扩展 : Get selected text

javascript - forEach 与 for in

javascript - 如何在指令中以 Angular 方式使用 jQuery?

javascript - 如何处理 Promise 模式中异步调用之前发生的错误?

javascript - AngularJS 和 Typescript 的 Promise

javascript - 如何在 Javascript 中模拟按下按钮以触发 Simple-Jekyll-Search 中的搜索

javascript - 执行 ajax 调用时丢失 mCustomScrollbar 效果