Pixark
Pixark

Reputation: 385

Angular - The easiest way to populate $scope

I am currently populating $scope arrays like this:

$scope.categories = [];

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

$scope.getCategories();

Is this really the easiest way to do it?

Upvotes: 0

Views: 233

Answers (2)

Jeff Hubbard
Jeff Hubbard

Reputation: 9892

You could simply use the resolve property of your router (assuming you're using a router) to inject the results from ItemService.getCategories() into your controller. resolve properties block the route from completing until they're fully resolved--it unwraps promises automatically. The code would look something like:

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

Upvotes: 0

Michael Low
Michael Low

Reputation: 24506

Do you actually need a getCategories function ? If this is the only place it's called, then you can just remove and leave the service call in directly.

Otherwise your code is as short as it gets for using promises I think, if you're using v1.2. Before 1.2, angular did have automatic promise unwrapping. That is, instead of

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

You could do this instead, which seems much more elegant:

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

Issues with this mean it's recently been removed though - https://github.com/angular/angular.js/issues/4158 . I think it's possible an alternative will be added in the future if there's a good way to do it though.

Upvotes: 3

Related Questions