Implementing double parentheses in the source code of an AngularJS input directive using JavaScript

I came across some unfamiliar syntax in the angularJs source code. Can someone provide an explanation for the expression within the parentheses of logical operators and dependency injection in "(inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer, $browser, $filter, $parse);"?

Here's the context:

var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
    function($browser, $sniffer, $filter, $parse) {
  return {
    restrict: 'E',
    require: ['?ngModel'],
    link: {
      pre: function(scope, element, attr, ctrls) {
        if (ctrls[0]) {
          (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer, $browser, $filter, $parse);
        }
      }
    }
  };
}];

Answer №1

When making a function call in JavaScript, the specific function being called is determined by the initial part of the code:

(inputType[lowercase(attr.type)] || inputType.text)

This concept is easier to understand with a concise example:

var functionToExecute = ...;
var obj = {
  goodbye: function(name) { alert('Goodbye ' + name); } 
  hello: function(name) { alert('Hello ' + name); }
};
(obj[functionToExecute] || obj.hello)(name);

If functionToExecute == 'goodbye', it will trigger obj.goodbye(name); if functionToExecute == 'hello', it will execute obj.hello(name). However, for any other value of functionToExecute, the default function called will be hello.

Answer №2

Perhaps a different perspective will help you grasp the concept:

var action = inputCategory[lowercase(attribute.category)];
if(!action) action = inputType.text;
action(scope, element, attribute, controllers[0], $sniffer, $browser, $filter, $parse);

|| is known as the logical OR operator. When used in expr1 || expr2, it will return expr1 if it can be interpreted as true; otherwise, it will return expr2.

Answer №3

This could possibly indicate that inputType[lowercase(attr.type)] refers to a function named inputType.text. The second set of parentheses likely contain the arguments for the function.

Take a look at this basic example of the inputType object in action.

var inputType = {
    text : function(scope, element, attr, ctrls, sniffer, browser, filter, parse){
        //perform tasks
    },
    button : function(scope, element, attr, ctrls, sniffer, browser, filter, parse){
        //perform tasks
    }
}

If the value returned by attr.type is not "text" or "button", it falls back to using the text function and executes it with the specified parameters.

Answer №4

Unfamiliar with the specific location in the angular source where this code resides, I am unsure of the exact whereabouts of the inputType object containing various functions for different input types, with its default set to text.

The following code:

(inputType[lowercase(attr.type)] || inputType.text)

makes use of the logical OR (||) operator. This operator returns the left operand if it is true; otherwise, it returns the right operand if the left one evaluates to false or undefined.

Essentially, this code looks up attr.type in the inputType object. If found, it returns that function; if not, it defaults to the function assigned to inputType.text. The arguments passed to this resulting function are enclosed in parentheses.

Using the || operator in this manner provides a convenient way to establish default values for incoming arguments. Another alternative you may have encountered is the ternary operator:

var func = inputType[lowercase(attr.type)] ? inputType[lowercase(attr.type)] : inputType.text;
func( scope, element, attr, ... );

In this scenario, the || version appears more sleek, especially when dealing with straightforward true/false conditions.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Express encounters an undefined value in req.body

My current challenge involves fetching POST data to my node.js server running express. I made sure to configure the bodyparser before setting up the routes: const express = require('express'), bodyParser = require('body-parser'), app = ...

Link the asp control as you input text into the Text box

I currently have a situation where I am working with a text box and a repeater control. My goal is to dynamically bind the data to the repeater control as the user types into the text box, without requiring them to press the enter key or click with the mou ...

Unusual functionality when utilizing angular-ui-bootstrap date in an angular-ui-modal

I'm currently working on my debut Angular app and I've hit a roadblock. While using ui-bootstrap date picker in various sections, everything worked fine. However, when I tried integrating it into a modal, an issue arose. After selecting a date c ...

Changing the value of a nested object in React's state

In my web application, I am using React/Redux with a Description Class that allows users to edit descriptions. The Props description and propertyTypes are fetched through AJAX calls. import React, { PropTypes } from 'react'; const defaultDesc ...

Tips for testing an Angular factory function

I am attempting to run a test on a factory using protractor and angular.mocks Below is the code for the factory: angular.module('googlemarker', []) .factory('newMarker', newMarkerFactory); newMarkerFactory.$inject = ['$windo ...

Is it possible to update the text in a select input from a dropdown menu within

In my example modal, I have included two components: a dropdown and an input text field. <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo">Test Modal</button> ...

I'm unable to locate my test text on the main page of my React web application

At the moment, my React application is running on port 3000 using npm start. I have made the decision to incorporate MySQL into the web app by executing yarn add express mysql. In order for this to work, I have configured server.js to listen on port 3001 ...

What is the best way to assign an onClick event in React while using document.createElement()?

I am using document.createElement to create an <input>. How can I assign the onClick property in React? var input = document.createElement("input"); input.onClick = {setCount()}; //??? Here is the React code snippet: <input type="s ...

Issue with reactivity in deeply nested objects not functioning as expected

Currently, I am utilizing Konvajs for my project. In simple terms, Konvajs provides a canvas for drawing and editing elements such as text nodes that can be manipulated by dragging and dropping. These nodes are organized within groups, which are then added ...

Having trouble getting the Pokemon modal to show both the type and image?

HTML: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>My First JS App</title> <lin ...

Changing a value to display with exactly 2 decimal places using jQuery

Similar Question: JavaScript: how to format a number with exactly two decimals Having successfully added values into a div with a total using some script, I attempt to convert those values into decimal numbers by dividing them by 100 to mimic currency ...

Mastering the utilization of componentDidMount and componentDidUpdate within React.js: a comprehensive guide

I am facing an issue. I need to find an index based on a URL. All the relevant information is passed to the components correctly, but I encounter an error after loading: Cannot read property 'indexOf' of undefined The JSON data is being transmi ...

Creating an array of a specific length and populating it with items in AngularJS can be achieved by first initializing an

By following this link, I was able to showcase the number of available slots in my app. However, what I actually need is to add items to these slots when a click event occurs and update the array. So far, I have assigned the function value to an array. ...

How to make an element active by default in AngularJS

I have designed a custom tabbed section by utilizing the code below: <div class="row step"> <div class="col-md-4 arrow active" ui-sref-active="active"> <a ui-sref="dashboard.create.key_elements" ui-sref-opts="{ reload: true }"&g ...

How about a unique scrolling experience?

Currently, I am attempting to prevent the scroll position from being locked after a single scroll for one second while scrolling down one section at a time. However, I am encountering unexpected behavior. const [nextSection, setNextSection] = useState(&ap ...

How can I display a customized HTML page for specific errors using Node.js and Express?

It seems that every time we deploy our servers, we experience a temporary 503 error for about 2-3 minutes while assets are being compiled. Is there a way to serve a static HTML page using Express/Node if the server returns a 503 error? Is there a simple ...

What is the best way to transmit real-time stdout data from a Node.js server to an AngularJS client?

I am currently facing an issue with a script that runs for a long time and generates output. The script is executed from nodejs using child_process, but I want to be able to send the output as soon as it starts executing without waiting for the script to c ...

Testing Mongoose Jasminejs unit for CRUD operations in DAOs

I'm currently in the process of developing a web application using Nodejs, Mongoose, and MongoDB, and I'm looking to conduct unit tests on my DAO methods using the Jasmine unit test framework. Here's a snippet of my model: var mongoose = r ...

Launching numerous websites in separate browser tabs using the window.open function

I have a code snippet that opens one tab pointing to a website, but I need it to open two. For example: www.google.com and www.yahoo.com Currently, it only works with one site in the code: window.open("https://www.google.com"); but not when bot ...

Maintain cookie data between pages to remember form inputs

The scenario: A form is utilized to capture the input value using $thisSearch.val(), store it as a cookie, and then add it to an array. This form is displayed as an overlay triggered from a menu item in the website header, allowing it to be accessed from a ...