在有角度的1.5组件中使用ControllerAs [英] using ControllerAs in an angular 1.5 component

查看:91
本文介绍了在有角度的1.5组件中使用ControllerAs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

在没有controllerAs的情况下一切正常.

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

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

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

推荐答案

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

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

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

这篇关于在有角度的1.5组件中使用ControllerAs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆