hurricane hurricane - 3 months ago 12
AngularJS Question

AngularJS Component define as function

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);

JSF JSF
Answer

You need to add parentheses to the last line like so:

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

Using simply getComponent (without parentheses) passes a reference to the getComponent function to component() without executing it. However, angular is expecting an object containing your component configuration.

Thus, passing getComponent() calls the function and returns the component configuration object passing said configuration object to angular component() initializer rather than a reference to the function getComponent.

Comments