3

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'
  }
})();
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
Bryan Dellinger
  • 4,724
  • 7
  • 33
  • 79

1 Answers1

6

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

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135