Hiding empty templates until the data is loaded with Restangular and UI-Router

Issue

I use ocLazyLoad to dependency injection and load CSS & JS on-demand. I would not change UI-Router state until the data has been loaded. Also I use Restangular to connect API.

Now how to call Restangular function from resolve state? It’s my route:

.state('admin.users',{
    url: "/users",
    templateUrl: "user/views/users.html",
    controller:'UserListCtrl',
    resolve: {
        dep: ['$ocLazyLoad',
            function( $ocLazyLoad ){
                return $ocLazyLoad.load(['UserService.js']).then(
                    function(){
                        return $ocLazyLoad.load(['UserListCtrl.js']);
                    }
                );
            }],
       resolvedItems: userlist()
    }
})

and my UserListCtrl is:

app.controller('UserListCtrl',function($scope,UserService){  

    /*
     * Get all users
     */
    userlist = function(){
        UserService.list().then(function(data){
             $scope.users = data;
             $scope.pagination = $scope.users.metadata;
             $scope.maxSize = 5;
        });
    }
})

and my UserService is:

angular.module('app').service('UserService', function($rootScope, Restangular) {
    /*
     * Build collection /user
     */
    var _userService = Restangular.all('user');


    /*
     * Get list of users
     */
    this.list = function() {
        // GET /api/user
        return _userService.getList();
    };
})

Solution

You cannot call a function from controller at config components. For waiting backend response for page openening you should use resolve feature of ui-router.

You already defined resolvedItems so make your userList request in there and resolve response like this…

resolve: {
    dep: ['$ocLazyLoad',
        function( $ocLazyLoad ){
            return $ocLazyLoad.load(['UserService.js']).then(
                function(){
                    return $ocLazyLoad.load(['UserListCtrl.js']);
                }
            );
        }],
   resolvedItems: ['UserService', function(UserService){
            return UserService.list().then(function(response){
                return response;
            })
        }]
}

and after it you should inject resolvedItems on you controller then page will not be shown until your request is completed…

Answered By – Poyraz Yilmaz

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.