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);
You need to add parentheses to getComponent passed as a parameter 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With