M.K. Safi
M.K. Safi

Reputation: 7039

AngularJS ui-router $state.go() not triggering state when "views" property is used

I have two parallel views in my AngularJS template. One is the main page view and the second is the navigation bar view. If user is logged in, I display private data in the main view as well as a link to user account in the navigation view. If user is not logged in, I display a welcome screen as well as a login link. So, that's why I'm using two parallel views.

When using ui-router with one ui-view directive in the template, things work as expected. When using two named ui-view directives in my template, $state.go('nameOfState') doesn't work anymore.

Here's a Plunk that's failing in triggering state with $state.go() because it has two views. Here's a Plunk that shows how the same code works when there's only one view.

Why is $state.go() not working?

Upvotes: 0

Views: 9904

Answers (1)

kong
kong

Reputation: 2011

The problem is the controller for your home state is not being instantiated, meaning the $state.go call is never happening. The controllers are instantiated only on demand. Specifically, the documentation states:

Warning: The controller will not be instantiated if template is not defined.

In order to get mainCtrl to be instantiated, you can add a template to the home state and add an unnamed ui-view to index.html, or you can add a template for one or more of the existing named views (e.g. "main") for the home state and move the mainCtrl to be the controller for those views. E.g. if you replace your existing home state with the following, it should work as expected:

.state('home', {
    url: '/',
    views: { 
      'main': {
        template: 'main template',
        controller: mainCtrl
      }
    }
  })

Upvotes: 2

Related Questions