In what manner does the AngularJS application define its components - modules, factories, and controllers?

I'm completely new to AngularJS and fairly new to JavaScript. I have a question about the example shown in a tutorial:

// Creates values or objects on demand
angular.module("myApp")     // Retrieves the "myApp" module from root.js (which injects the "serviceModule" service)
.value("testValue", "AngularJS Udemy")

// Defines a factory named "courseFactory" which takes in testValue as input
.factory("courseFactory", function(testValue) {
    // The factory creates a JSON object called "courseFactory";
    var courseFactory = {
            'courseName': testValue,    // Injected value
            'author': 'Tuna Tore',
             getCourse: function(){     // A function within a JSON object
             alert('Course: ' + this.courseName);   // Call a function within the object
            }
          };    
    return courseFactory;       // Returns the created JSON object
})

// Controller named "factoryController" injections $scope service and the "courseFactory" factory:
.controller("factoryController", function($scope, courseFactory) {
    alert(courseFactory.courseName);        // Pop-up with courseName from factory
    $scope.courseName = courseFactory.courseName;
    console.log(courseFactory.courseName);
    courseFactory.getCourse();  // Second alert message
});

The concept is clear: create an angular module for my application called myApp. Then define a value, a factory (which returns a courseFactory JSON object), and finally a controller that uses the factory.

What's unclear to me is the syntax of these component declarations.

It seems like the syntax follows this pattern:

angular.module("myApp").value(VALUE DECLARATION).factory("courseFactory", function(testValue) { RETURN THE JSON OBJECT IMPLEMENTING THE FACTORY }).controller("factoryController", function($scope, courseFactory) { IMPLEMENT THE CONTROLLER });

My question is: why are all these components (the value declaration, factory implementation, and controller implementation) chained together using "."?

What does this "." mean exactly?

I believe it's adding a field to an object or something similar, but it's confusing to me.

Initially, there's the angular object (is it an object?) to which the module("myApp") component is added (making sense since it adds a module to Angular).

Then a value is added as a property of this module, which also makes sense as it adds a value to a specific module.

But why then add a factory as a field of this value, followed by adding the controller as a field of this factory?

I feel like I'm missing something.

What am I missing? How does the AngularJS component definition really work?

Answer №1

When you call:

angular.module("myApp")

You will receive the object that represents the module.

To check this, you can use:

console.log(angular.module("myApp"));

You'll notice that this object contains various methods such as value, controller, and factory.

This is why you're able to do things like:

angular.module("myApp").value("testValue", "AngularJS Udemy");

The key here is that the value method also returns the module object so you can continue chaining:

angular.module("myApp").value("testValue", "AngularJS Udemy").factory(...)

The same concept applies to the other methods of the module object.

This approach of having methods return the main object is commonly used to enable this type of chaining.

You can interpret it like this:

var myModule;

myModule = angular.module('myApp'); // Gets the module

myModule = myModule.value(...); // Adds a value and gets back the module

myModule = myModule.factory(...); // Registers a factory and retrieves the module

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

Creating and accessing a JSON file with Perl and JavaScript: A step-by-step guide

I'm feeling uncertain about whether or not I have gone about this the right way. I have crafted a Perl script that takes basic data and generates a JSON formatted output. Testing it locally in the shell shows that the output is correct when using a pr ...

Develop a Vue.js component embedded within another component to manipulate data stored in the parent

After reviewing a few answers that partially address my question, I realized there is more to explain. In our Laravel project website layout, we utilize a global #app div. This means all pages share the same main Vue instance, prompting me to segregate ke ...

Format the date using the Datepicker

I am looking to update the date format in my date picker from "12/25/2022" (for example) to "25/December/2022" Here is the code I have: $(".date-picker").datepicker({ format: 'dd-mm-yyyy', minDate: 0, numberOfMonths: \[3,1&b ...

Removing a Firestore Document when the identifier is assigned to a unique name that is not predefined in any location

Presently, my database stores user information. The unique identifier for each document is the user's initial name upon registration, even though this name may have been changed at a later time without updating the document's name. My dilemma is ...

Unable to access elements located underneath the div

I'm working on creating a simple menu using CSS and jQuery. Everything seems to be functioning correctly, but I've noticed that when I open the menu, I am unable to click on any elements below it. Check out the menu here <header> <nav ...

Include a link to a JavaScript file within a dynamically created HTML page in a Delphi VCL application

I am currently developing a Delphi XE5 VCL Forms Application which includes a TIdHTTPServer on the main form. Within this server, there is a CommandGet procedure called IdHTTPServer: procedure TForm1.IdHTTPServerCommandGet(AContext: TIdContext; ARequest ...

What is the proper way to create an empty key in a JSON object using JavaScript?

If you were to work with this JSON object {"":"some text"} How would you access its data using JavaScript? json_obj={"":"some text"} alert(json_obj.) I'm struggling with this, any assistance is appreciated! ...

Content is deleted by ng-bind-html following the < symbol (less than sign)

In my current project using angular v1.5.6, I have html data entered by users with special characters which are stored in the database. For example: var txt = "<span class='txt_bold'> content with <lessthan signs<span> <span> ...

Is there an issue with Three.js canvas.toDataURL() function in Chromium browsers?

After performing a recent system upgrade, I noticed some issues with Chromium. One of them was a delay in loading my Three.js r85 project, which was resolved after upgrading to Three.js r90. However, I encountered a new problem with toDataUrl() not workin ...

box tick does not alter appearance

I've been struggling with this seemingly simple issue for an hour now. I have a radio button set up with two buttons: <input class="form-control icheck" id="cash_prize" name="cash_prize" type="radio" value="1" style="position: absolute; opacity: 0 ...

JavaScript Navigation Bar Error: The value of 'undefined' is not recognized as an object

Having just started learning HTML, CSS, and JavaScript, I encountered an error message that reads: TypeError: 'undefined' is not an object. Despite my best efforts to troubleshoot the issue, I have been unable to resolve it. Is there anyone who c ...

Using JavaScript to handle JSON data processing

Does anyone know the best way to access JSON data using JavaScript? I've attempted to use the $.each loop and tried accessing with [0], but all I get is undefined. Here is the JSON data from the controller: { "workers": { "107": "Lisa", ...

Dealing with Javascript exceptions and sending email notifications in Django

I appreciate the traditional method of handling server-side exceptions in Django using Python. I am interested in finding a similar approach for client-side exception handling in JavaScript. So far, I have come across only one option which is DamnIT, but ...

How to trigger useEffect when the state changes to the same value using React hooks?

Currently working on a drum-pad app, most features are functional except for one small issue. Quick update: Uploaded the project to codesandbox for anyone willing to take a look: codesandbox.io/s/sleepy-darwin-jc9b5?file=/src/App.js const [index, setIndex ...

secure communication with web socket utilizing spring boot and angular for one-on-one messaging

I am developing a secure messaging system for individual conversations. On the server side: @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker("/topic", "/queue", "/user"); config.set ...

Nested asynchronous mapping in Node.js involving multiple HTTP requests

Currently, I am attempting to iterate through an array of URLs and retrieve responses from a specific set of URLs. The goal is for the outer loop to only proceed after all inner requests have been completed, resulting in the desired outcome as shown below: ...

JavaScript/jQuery Progress Bar for Tracking File Downloads

I've been working on a project that involves downloading multiple files as a single zip file using the JSZip plugin. However, during the download process, the browser freezes up and I'd like to implement a progress bar to indicate how far along t ...

Leveraging promises to make Ajax calls without repeating code

Would it be possible to create an ajax function without duplicating it? Passing different parameters, which are locations to various files. Then utilizing the promise to combine them into a single object, possibly incorporating the spread operator. Is th ...

How to iterate through a Vue data object using forEach loop

I am currently working with a variable in my data: data: function () { return { myVariable: false, } } I'm trying to figure out how to access this variable within a looping function, like the example below: anArray.forEach(functi ...

Display an image when hovering over a list in HTML, utilizing JS and JQuery

When I hover over the text, I want those images to become visible. However, it seems that only the first image is selected because they all have the same ID. Does anyone know how to solve this issue? This is my first post, so please forgive me if I made ...