using ControllerAs in an angular 1.5 component

女生的网名这么多〃 提交于 2019-12-22 10:03:09

问题


I am attempting to use the controllerAs Syntax in an angularjs 1.5 component.

here is a plunker https://plnkr.co/edit/mTa1bvoNi1Qew9l1xAFS?p=preview

without the controllerAs everything works fine.

(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.

(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'
  }
})();

回答1:


You should specify the controllerAs as property, like this:

(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

For more info: https://alexpeattie.com/blog/setting-the-default-controlleras-to-vm-for-component-angular-1-5



来源:https://stackoverflow.com/questions/47000862/using-controlleras-in-an-angular-1-5-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!