Angular 从 html 引用没有 $scope 的控制器

Angular referencing controller from html without $scope

我正在使用新的 angular,正如我被告知的那样 - 我正在摆脱 $scope 对象。

因此,当我从 html 页面引用我的控制器时,我使用别名引用它:

<div ng-controller="MyController as ctrl">
    <p>{{ ctrl.Hello }}</p>
</div>

我的问题是:当我使用路线时,我将其中一条路线声明为:

$stateProvider.state('myPage', {
  url: "/myPage",
  templateUrl: "./views/myPage.html",
  controller: 'MyController'
  })

在这种情况下不使用 $scope 引用控制器的合适方法是什么?

ui-路由器支持 controllerAs 和 属性。

$stateProvider.state('myPage', {
  url: "/myPage",
  templateUrl: "./views/myPage.html",
  controller: 'MyController',
  controllerAs: 'ctrl'
})

更多信息 https://github.com/angular-ui/ui-router/wiki

使用带有 "controller as" 语法和 vm 变量的控制器:

function MyController() {
    // VM represents the View’s Model (aka ViewModel)
    var vm = this;

   // exports
   vm.item = "Test item";

   return vm;
}
  • 创建一个没有 $scope 的控制器。
  • this 分配给局部变量。我更喜欢vm作为变量名,你可以选择任何你喜欢的名字。
  • 将数据和行为附加到 vm 变量。
  • view 上,使用控制器作为语法为控制器指定别名。
  • 您可以为别名指定任何名称。除非我不使用嵌套控制器,否则我更喜欢使用 vm。