Hao
Hao

Reputation: 6609

Use Angular ui-router for heavy template

I have a controller which is used to back a couple of templates on different route. These html templates are quite heavy as they contain large table with many rows plus some controller logic manipulating the table cells which causes this:

  1. When I first load the page in browser, and I switch to a new route, the route change fast, then the page slowly slowly finished loading.
  2. Then, if I switch back and forth to the previous route, the route basically freezes, then BOM!!, the route changes, and I see the new route with the page already loaded.

I am using the basic route set up like in the tutorial. I think I am using it wrong. The ui-router is too busy registering and de-registering my templates within this single ui-view.

<body ng-app="helloworld">
<a ui-sref="hello" ui-sref-active="active">Hello</a>
<a ui-sref="about" ui-sref-active="active">About</a>

<ui-view></ui-view>

and

var myApp = angular.module('helloworld', ['ui.router']);

myApp.config(function($stateProvider) {
  var helloState = {
    name: 'hello',
    url: '/hello',
    templateUrl: 'slowRoute1'
  }

  var aboutState = {
    name: 'about',
    url: '/about',
    templateUrl: 'slowRoute2'
  }

  $stateProvider.state(helloState);
  $stateProvider.state(aboutState);
});

What should be the correct way to wire such kinds of heavy routes?

Upvotes: 1

Views: 43

Answers (2)

Ladmerc
Ladmerc

Reputation: 1158

Using resolve as suggested means that the view will not be entered unless the resolves gets resolved.

Another option if especially the table rows are generated dynamically, is to use the $stateChangeSuccess event listener to only call the heavy controller function when the state has been successfully transitioned to. You can load a shell page here and populate when the controller returns data

https://github.com/angular-ui/ui-router/wiki#user-content-state-change-events

Upvotes: 1

Aayushi Jain
Aayushi Jain

Reputation: 2879

You can make use of resolve, this will not load your page until whatever written in resolve loads, for example:

$stateProvider.state('users.profile', {
  url: '/:id',
  templateUrl: 'views/users.profile.html',
  controller: 'UsersController',
  resolve: {
    user: function($stateParams, UserService) {
      return UserService.find($stateParams.id);
    },
    tasks: function(TaskService, user) {
      return user.canHaveTasks() ?
        TaskService.find(user.id) : [];
    }
  }
}); 

In this, the page won't load until the user and tasks functions are executed.

And for your reloading issues, you may use $state.reload() method. This feature does not re-initialize the controller, which means the resolves will reload, but your scope properties won’t be updated accordingly.

Upvotes: 1

Related Questions