【问题标题】:AngularJS Component define as functionAngularJS 组件定义为函数
【发布时间】:2017-01-08 01:03:03
【问题描述】:

当我使用返回 component 对象的函数创建组件时,我的组件未初始化!我正在分享这两种情况。谁能解释一下它们之间有什么区别?

HTML:

<div ng-app="demoApp">
  <navbar></navbar>
</div>

工作代码:Fiddle

var NavbarTemplate = `<button ng-click="$ctrl.clickTest()">Click Test</button>`;
var navbar = {
  controller: function() {
    this.clickTest = clickTest;
    function clickTest() {
      alert("hello");
    }
  },
  template: NavbarTemplate
};
angular.module('demoApp', []).component('navbar', navbar);

错误(无错误)代码:Fiddle

function getComponent(){
    var template = `<button ng-click="$ctrl.clickTest()">Click Test</button>`;
    var component = {
    controller: function() {
      this.clickTest = clickTest;
      function clickTest() {
          alert("hello");
        }
    },
    template: template
  }
  return component;
}
angular.module('demoApp', []).component('navbar', getComponent);

【问题讨论】:

  • 您不应该将对象文字传递给它吗?试试.component('navbar', getComponent())
  • @Daniel_L 感谢您的回答。我试过了,它奏效了。我熟悉使用指令:)。

标签: javascript jquery angularjs angular-components


【解决方案1】:

您需要将括号添加到getComponent 作为参数传递到最后一行,如下所示:

angular.module('demoApp', []).component('navbar', getComponent());

简单地使用getComponent(不带括号)将getComponent函数的引用传递给component()而不执行它。但是,angular 需要一个包含您的组件配置的对象。

因此,传递getComponent() 调用函数并返回组件配置对象,将所述配置对象传递给角度component() 初始化器,而不是对函数getComponent 的引用。

【讨论】:

    猜你喜欢
    • 2018-05-01
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    • 2022-07-22
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多