Angular - 填充$ scope的最简单方法

时间:2013-11-15 14:05:08

标签: angularjs

我目前正在填充$scope这样的数组:

$scope.categories = [];

$scope.getCategories = function() {
    ItemService.getCategories().success(function(categories) {
        $scope.categories = categories;
    });
}

$scope.getCategories();

这真的是最简单的方法吗?

2 个答案:

答案 0 :(得分:3)

你真的需要一个getCategories函数吗?如果这是它被调用的唯一地方,那么您可以直接删除并保留服务电话。

否则,如果您使用的是v1.2,那么您的代码就像我认为的使用promises一样短。在1.2之前,角度确实有自动承诺解开。也就是说,而不是

//$scope.getCategories = function() {
    ItemService.getCategories().success(function(categories) {
        $scope.categories = categories;
    });
//}

你可以这样做,这看起来更优雅:

//$scope.getCategories = function() {
    $scope.categories = ItemService.getCategories();
//}

这个问题意味着它最近被删除了 - https://github.com/angular/angular.js/issues/4158。我认为,如果有一个很好的方法,将来可能会增加一个替代方案。

答案 1 :(得分:0)

您可以简单地使用路由器的resolve属性(假设您正在使用路由器)将ItemService.getCategories()的结果注入您的控制器。 resolve属性阻止路由完成直到它们完全解析 - 它会自动解包承诺。代码看起来像:

angular.module('MyModule').config(function ($routeProvider) {
    $routeProvider.when('/mypage', {
        templateUrl: '/mypage.html',
        controller: 'MyController',
        resolve: {
            categories: function (ItemService) { return ItemService.getCategories(); }
        }
    });
});

angular.module('MyModule').controller('MyController', function (categories, $scope) {
    $scope.categories = categories;
});