2

Following the tutorial :

http://scotch.io/tutorials/javascript/angular-routing-using-ui-router

and the demo :

http://scotch.io/demos/angular-ui-router#/about

On the about page , there are two named views, "columnOne" and "columnTwo".

Is it possible to instantiate the named views conditionally , If some condition fails the named view "columnOne" and its controller shouldnt instantiate and its place be left empty on the page.

I would like to avoid the use of ng-if on the as do not wish the controller to load thus saving on the API calls the controller might have.

Something like rejecting in a resolve block but for sibling named views.

hussainb
  • 1,218
  • 2
  • 15
  • 33

1 Answers1

2

UI Router provides us with two "secret sauces", templateProvider function and the $templateFactory service.

The template provider function which can be injected, has access to locals, and must return template HTML.

So, within this function you can set your conditionals to render a template for a named view. templateProvider() only allows us to return HTML, but let's say we want to return a template for the sake of readability or whatever reason you might have. That's where we'd use $templateFactory and call .fromUrl() on it:

$templateFactory.fromUrl() loads a template from the a URL via $http and $templateCache.

views: {
  'columnOne': {
    controller: 'SomeCtrl',
    templateProvider: function($templateFactory) {
      // if condition is true, return the template for column one
      return $templateFactory.fromUrl('path/to/template.html');
    }
  },
  'columnTwo': {
    controller: 'MaybeSomeOtherCtrl',
    templateProvider: function($templateFactory) {
      // if condition is true, return the template for column two
      return $templateFactory.fromUrl('path/to/template.html');
    }
  }
}
Desmond
  • 1,532
  • 15
  • 25