简体   繁体   English

在1.5角度组件中使用ControllerAs

[英]using ControllerAs in an angular 1.5 component

I am attempting to use the controllerAs Syntax in an angularjs 1.5 component. 我正在尝试在angularjs 1.5组件中使用controllerAs语法。

here is a plunker https://plnkr.co/edit/mTa1bvoNi1Qew9l1xAFS?p=preview 这是一个小矮人https://plnkr.co/edit/mTa1bvoNi1Qew9l1xAFS?p=preview

without the controllerAs everything works fine. 没有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'
  }
})();

however attempting to change to controllerAs and I no longer get the bindings. 但是尝试更改为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'
  }
})();

You should specify the controllerAs as property, like this: 您应该将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://plnkr.co/edit/ThIvAnLJFhucckcRvQ3N?p=preview

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM