Tyler L
Tyler L

Reputation: 845

Why does my function need parentheses?

In my framework, the functions are called without parentheses.... (See showErrors)

(function () {
  'use strict';

  angular
    .module('core')
    .directive('showErrors', showErrors);

  showErrors.$inject = ['$timeout', '$interpolate'];

  function showErrors($timeout, $interpolate) {
    var directive = {
      restrict: 'A',
      require: '^form',
      compile: compile
    };

    return directive;

I get how it works... but when I try this, my component won't work. It only works if I change it to .component('hotkeys', HotkeysComponent()); // adding parenthesis to HotkeysComponent

  angular
    .module('contacts.components')
    .component('hotkeys', HotkeysComponent);

  function HotkeysComponent() {
    var component = {
      templateUrl: '/my-app/contacts/client/views/ui/hotkeys.ui.html',
      controller: 'AddManagerController',
      controllerAs: 'vm'
    };

    return component;

To clarify, it won't work unless I do HotkeysComponent()

angular
  .module('contacts.components')
  .component('hotkeys', HotkeysComponent()); // why don't the other functions need ()?

Upvotes: 1

Views: 104

Answers (2)

Ram_T
Ram_T

Reputation: 8484

Components can be registered using the .component() method of an AngularJS module (returned by angular.module()). The method takes two arguments:

  • The name of the Component (as string).
  • The Component config object. (Note that, unlike the .directive() method, this method does not take a factory function.)

As per your question, the second argument must be an object and that happens only when you called the function(second argument)

Components in angular js read this for more info

Upvotes: 1

Bas van Dijk
Bas van Dijk

Reputation: 10713

There is a big difference between the two. HotkeysComponent as a parameter gives the function pointer, while HotkeysComponent() is the value HotkeysComponent returns.

An example:

testFunction(variable) {
    variable();
}

testFunction(alert);

Here we pass alert as a function (not the return value). Now we can execute this function inside testFunction.

testFunction(variable) {
    console.log(variable);
}

sum(x, y) {
    return x + y;
}

testFunction(sum(10,20));

Here we pass the outcome of the sum function to the function, which we can use inside our testFunction.

Upvotes: 0

Related Questions