使用ui-router的'controller as'不能按预期工作

Hom*_*rew 23 angularjs angular-routing angular-ui-router

对于使用抽象状态和控制器作为语法的页面,我有以下状态设置:

# 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'
Run Code Online (Sandbox Code Playgroud)

为了这个演示的目的,我可以说我将一个变量分配给'Title'控制器的't'实例,我在Title控制器函数中执行此操作.

angular.module('title').controller 'Title',
 ['$state', ($state) ->
   this.name = 'Test'
Run Code Online (Sandbox Code Playgroud)

在我的视图'title/show.html'中,我尝试打印出刚刚创建的变量到页面:

{{t.name}}
Run Code Online (Sandbox Code Playgroud)

我什么都没看到.但是,如果我将ui-router的控制器移到包含'title/show.html'页面的元素上,如下所示:

<div ng-controller="Title as t">
Run Code Online (Sandbox Code Playgroud)

一切都很好.有没有人遇到过这个问题.我在其他应用程序中工作正常,所以我仍然想弄清楚这个应用程序可能有什么不同,可能是js库版本的差异.

Mic*_*zos 43

在您的州配置中:

而不是controller: 'Title as t',尝试:

controller: 'Title',
controllerAs: 't'
Run Code Online (Sandbox Code Playgroud)

编辑:刚刚实现了一个最小的应用程序,ui-router并且语法controller: Title as t也可以使用,版本0.2.0 ui-router到今天的最新版本.t当我检查角度范围时,我可以看到实例.

  • 考虑到控制器不应该是问题:ui-router支持"ctrl as ctrl",请参阅https://github.com/angular-ui/ui-router/wiki#controllers (4认同)
  • 是的,我已经尝试过控制器,但仍然存在同样的问题。 (2认同)

Nic*_*win 12

您的控制器需要返回值,this以便controllerAs功能正常工作.由于CoffeeScript隐式返回最后一行,您需要编写:

return this
Run Code Online (Sandbox Code Playgroud)

或者如果您使用的是vm语法并且已写入:

vm = this
Run Code Online (Sandbox Code Playgroud)

你可以在控制器的最后写:

return vm
Run Code Online (Sandbox Code Playgroud)


小智 10

如果这有助于任何人我的问题来自使用模板化视图,但在views元素之外指定controllerAs.这需要永远弄明白.相信这个主题https://github.com/driftyco/ionic/issues/3058

**错误**

views: {'content@': { templateUrl: 'views/listing.html' }},
controller: 'ListingCtrl',
controllerAs: 'ctrl'
Run Code Online (Sandbox Code Playgroud)

**对**

views: {
  'content@': { templateUrl: 'views/listing.html' },
   controller: 'ListingCtrl',
   controllerAs: 'ctrl'
}
Run Code Online (Sandbox Code Playgroud)