When i create a component with a function which is returning a component object, my component is not initialize! I am sharing these two situation. Can someone explain me what is the difference between them?
Html:
<div ng-app="demoApp">
<navbar></navbar>
</div>
Working code: 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);
Faulty (without error) code: 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);
答案 0 :(得分:1)
您需要将作为参数传递的getComponent
的括号添加到最后一行,如下所示:
angular.module('demoApp', []).component('navbar', getComponent());
简单地使用getComponent
(不带括号)将getComponent
函数的引用传递给component()
而不执行它。但是,angular需要一个包含组件配置的对象。
因此,传递getComponent()
会调用该函数并返回将所述配置对象传递给angular component()
初始值设定项的组件配置对象,而不是对函数getComponent
的引用。