Angular的"controllerAs"在routeProvider中不起作用

tha*_*las 9 angularjs angularjs-routing

我试图controllerAs$routeProvider路线上使用该属性,但没有任何成功.

以下是示例代码:

var app = angular.module('app', ['ngRoute']);

app.config(['$routeProvider', '$locationProvider',
  function($routeProvider) {
  $routeProvider
    .when('/', {
      template:'<div>This should be visible:{{ ctrl.one }}</div><div>This should not:{{ one }}</div>',
      controller: 'Ctrl',
      controllerAs: 'ctrl',
    });
}]);

app.controller('Ctrl', function($scope) {
  $scope.one = 'actual';
});
Run Code Online (Sandbox Code Playgroud)

不确定这是一个错误还是我做错了什么,这是一个展示问题的plnkr

Roh*_*ner 15

实际问题:

您似乎最初使用controllerAs(赋值'ctrl'),但后来在其余代码中没有使用它.(你用过$scope)

在此输入图像描述

解:

根据您的样本进行演示

当我一直在使用controllerAs语法时,您需要使用以下模式之一来访问控制器的实例:

与附加属性相反$scope,您必须绑定到控制器范围.注意这是不同的$scope.由于缺少更好的术语,您需要绑定控制器本身(将其视为其上下文).当我们处理显示层或视图模型时,我倾向于使用var vm = this;作为约定,但这个个人偏好.

[A]:首选解决方案

app.controller('Ctrl', function() {        
    this.one = 'actual';  
});

//or using 'vm' convention

app.controller('Ctrl', function() {
    var vm = this;
    vm.one = 'actual';  
});
Run Code Online (Sandbox Code Playgroud)

[B]

app.controller('Ctrl', function() {
    var vm = {};
    vm.one = 'actual';
    return vm;
});
Run Code Online (Sandbox Code Playgroud)

说明:

当我第一次开始使用Angular时,[B]是我使用的方法,纯粹来自Knockout背景.我习惯于绑定到"容器"对象,然后将对象绑定到视图.话虽这么说,我更喜欢使用[A],或者直接追加$scope并完全放弃别名.原因:

  • 我觉得它更清洁的ITO可读性
  • 正如@ Swordfish0321所述,[A]性能更高(如果你担心的话)
  • 我有自定义指令的绑定问题,我写的是依赖于某些父作用域属性(特定于我的代码库)

就像一个视觉:

演示

 app.controller('Ctrl', function($scope) {
      var vm = this;
      vm.one = 'actual'; 
      console.log($scope) 
 });
Run Code Online (Sandbox Code Playgroud)

传入$scope对象并进一步检查它,您将看到一个新的ctrl子对象,其中包含绑定到vm控制器代码中的所有公共属性和函数.这是因为你已经分配了var vm = this.意味着vm代码中的对象引用控制器自己的范围,最终绑定到视图.controllerAs基本上将控制器内部包含的所有属性和函数分组到以您提供的别名命名的新对象.

在此输入图像描述