Using 'controller as' with the ui-router isn't working as expected

HomeBrew picture HomeBrew · Mar 9, 2015 · Viewed 20.9k times · Source

I have the following state setup for a page using an abstract state and the controller as syntax:

# Details page route
.state 'title', 
  url: '/title',
  abstract: true,
  template: '<ui-view/>',
.state 'title.show', 
  url: '/:titleId',
  templateUrl: 'title/show.html'
  controller: 'Title as t'

For the purpose of this demo lets say I assign a variable to the 't' instance of the 'Title' controller and I do this inside of the Title controller function.

angular.module('title').controller 'Title',
 ['$state', ($state) ->
   this.name = 'Test'

and inside my view 'title/show.html' I attempt to print out that variable I just created to the page:

{{t.name}}

I don't see anything. But if I remove the controller our of the ui-router and onto the element that wraps the 'title/show.html' page like this:

<div ng-controller="Title as t">

Then everything works great. Has anyone come across this problem before. I have it working fine in another app so I'm still trying to figure out what might be different in this app, maybe a difference in js library versions.

Answer

Michael P. Bazos picture Michael P. Bazos · Mar 10, 2015

In your state configuration :

Instead of controller: 'Title as t', try :

controller: 'Title',
controllerAs: 't'

Edit : Just implemented a minimal app with ui-router and the syntax controller: Title as t also works, in versions 0.2.0 of ui-router to the most recent one as of today. I can see the t instance when I inspect angular scopes.