Last Updated: September 09, 2019
· otupman

AngularJS UI Router with named views & abstract controllers

Wow, that title's a mouthful.

Basically this post is possibly for you if:

  1. You're using AngularJS (applicable to Ionic as well)
  2. You're using the shiny AngularJS UI Router
  3. You're using named views
  4. You want to create an abstract state
  5. You want the abstract state to have a controller


You must declare your controller at the named view data (i.e. with the template you'll use) and not at the 'normal' level.

abstract: true, url: '/app', views: {'filters': { controller: 'Ctrl', ... } }

The UI Router docs have this gem buried in them: "Warning: The controller will ** not ** be instantiated if template is not defined". If you've used UI Router you've typically found that you define your controller at the level of the rest of your state:

  .state('report', {
    // url, template, templateUrl, etc.
    controller: 'ReportCtrl'

This will not work when using named views (which makes sense considering that a controller is typically paired with a single template). The following config would set the ReportViewCtrl for the 'filters' view:

  .state('report', {
      // url, template, templateUrl, etc.
      views: {
        'filters': { 
          controller: 'ReportViewCtrl', // HERE
          template: '<p>Template here</p>'

This is mentioned in the docs, but after 30mins of playing I never saw it. So be warned!