Tuesday, 2 February 2016

UI Router resolves vs loading data in controller

So, What's the basic difference between running code when a controller starts and running code in a route resolver?
The basic difference is when a controller starts activation happens after the route and when we use route resolver activation happens before the route.
There may be many cases when you need to use route resolver to run few functions or ajex calls before the controller gets activated.
Those cases could be like
  • When you want to validate user crediantial.
  • Run controllers only after initialization is completed,
  • When your page elements blink due to changine routes.

Then for those cases we can use Use AngularUI Router and nested resolves to move data-loading logic out of the controller and avoid code duplication and coupling between controllers.
So how it's done... You can follow the below snippet. The code is self explanatory

2 comments:

  1. Is there a way to show some ajax wait message during Resolve ?

    ReplyDelete
    Replies

    1. Yes.. The API provides you with two event hooks: $stateChangeStart and $stateChangeSuccess. We can use them in main controller like.

      $scope.showSpinner = false;

      $scope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
      if (toState.resolve) {
      $scope.showSpinner =true;
      }
      });
      $scope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
      if (toState.resolve) {
      $scope.showSpinner = false;
      }
      });


      I update the fiddle also.

      Delete