javascript - AngularJS 错误 : Cannot use 'in' operator to search for '$ctrl' in

标签 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: '&'
    }
  });

最佳答案

这里已经回答了类似的问题:AngularJS Directive element method binding - TypeError: Cannot use 'in' operator to search for 'functionName' in 1

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

<question on-click="$ctrl.updateLastName(lastName)">

并且在您的组件中,您需要使用包含姓氏的 JSON 调用您的函数:

<button ng-click="$ctrl.onClick({lastName: $ctrl.input})">

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

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

关于javascript - AngularJS 错误 : Cannot use 'in' operator to search for '$ctrl' in,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48494937/

相关文章:

javascript - 如何从一系列日期范围(可能有重叠的工作日期)中查找某人的工作经验年数

javascript - if 语句匹配数组

javascript - ng-view 在 Angular 中不起作用

javascript - ng 类验证在 AngularJS 中不起作用

javascript - jquery滑动菜单,默认折叠所有菜单

javascript - iphone webview 和 iframe 问题

javascript 优化和缩小 vs. gzipping

javascript - ionic 模板内容未显示

angularjs - window.ATL_JQ_PAGE_PROPS 在JQgrid

javascript - 如何为新添加的行添加背景颜色angularjs