AngularJS错误:无法使用'in'运算符来搜索'$ ctrl'

Jon*_*Jon 6 javascript angularjs

我有一个directory组件将一个函数传递给question组件.的question部件是把一个输入,然后更新directory与通过函数这个输入部件.当question组件尝试访问此函数时,存在JS错误:angular.min.js:123 TypeError: Cannot use 'in' operator to search for '$ctrl' in Lee.我做错了什么来触发这个错误?

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

let directoryTemplate = 
  '<question on-click="$ctrl.updateLastName()"></question>' +
  '<br />' +
  'Full name: {{$ctrl.fullName}}';

class directoryController {
  constructor() {
    this.fullName;
    this.firstName = 'Jack';
  }
  updateLastName(lastName) {
    this.fullName = `${this.firstName} ${lastName}`;
  }
}


let questionTemplate = 
  '<input ng-model="$ctrl.input" />' +
  '<button ng-click="$ctrl.onClick($ctrl.input)">Submit</button>';

class questionController {
  constructor() {
    this.input;
  }
}


angular
  .module('app', [])
  .component('directory', {
    template: directoryTemplate,
    controller: directoryController
  })
  .component('question', {
    template: questionTemplate,
    controller: questionController,
    bindings: {
      onClick: '&'
    }
  });
Run Code Online (Sandbox Code Playgroud)

Fl4*_*l4v 10

这里回答了一个类似的问题:AngularJS指令元素方法绑定 - TypeError:不能使用'in'运算符来搜索1中的'functionName'

简而言之,在调用组件的模板中,您需要传递函数的签名(包括参数的名称):

<question on-click="$ctrl.updateLastName(lastName)">
Run Code Online (Sandbox Code Playgroud)

在您的组件中,您需要使用包含lastName的JSON调用您的函数:

<button ng-click="$ctrl.onClick({lastName: $ctrl.input})">
Run Code Online (Sandbox Code Playgroud)

查看上传的plunker:https://plnkr.co/edit/iOA29KGEbl6NLubP1cvb p = preview

顺便说一下,您应该为多行模板使用ES6模板字符串,就像您对updateLastName方法所做的那样(请参阅https://developers.google.com/web/updates/2015/01/ES6-Template-Strings).