在 angular 1.5 组件中使用 ControllerAs

using ControllerAs in an angular 1.5 component

我正在尝试在 angularjs 1.5 组件中使用 controllerAs 语法。

这是一个笨蛋https://plnkr.co/edit/mTa1bvoNi1Qew9l1xAFS?p=preview

没有 controllerAs 一切正常。

(function() {
  angular.module("myApp", [])
    .component("helloWorld", {
      template: "Hello {{$ctrl.name}}, I'm {{$ctrl.myName}}!",
      bindings: {
        name: '@'
      },
      controller: helloWorldController
    })

  function helloWorldController() {
    /* jshint validthis: true */
    var vm = this;
    vm.myName = 'Alain'
  }
})();

但是尝试更改为 controllerAs,我不再获得绑定。

(function() {
  angular.module("myApp", [])
    .component("helloWorld", {
      template: "Hello {{vm.name}}, I'm {{vm.myName}}!",
      bindings: {
        name: '@'
      },
      controller: ('helloWorldController', helloWorldController)
    })

  function helloWorldController() {
    /* jshint validthis: true */
    var vm = this;
    vm.myName = 'Alain'
  }
})();

您应该将 controllerAs 指定为 属性,如下所示:

(function() {
  angular.module("myApp", [])
    .component("helloWorld", {
      template: "Hello {{vm.name}}, I'm {{vm.myName}}!",
      bindings: {
        name: '@'
      },
      controller: ('helloWorldController', helloWorldController),
      controllerAs: 'vm'
    })

  function helloWorldController() {
    /* jshint validthis: true */
    var vm = this;
    vm.myName = 'Alain'
  }
})();

https://plnkr.co/edit/ThIvAnLJFhucckcRvQ3N?p=preview

更多信息:https://alexpeattie.com/blog/setting-the-default-controlleras-to-vm-for-component-angular-1-5