HomeBlogWeb DevelopmentModule in AngularJS Explained with Examples

Module in AngularJS Explained with Examples

Published
05th Sep, 2023
Views
view count loader
Read it in
8 Mins
In this article
    Module in AngularJS Explained with Examples

    A module in Angular is a collection of connected components, directives, pipes, and services that may be used to build an application. An Angular application's element (or module) must be present to view the whole image. 

    Classes are an excellent example for Angular modules, as well. In a class, we can make a method public or private. While the public methods represent the API that the other portions of our code may use to connect with it, their implementation is kept private. 

    Like components and directives, pipes or services may be exported or hidden by a module. It is important to note that the exported components may be used by external modules, while the module can only use those that are not imported (hidden). 

    What are Angular Modules?

    Modules are containers used to build applications. An essential benefit of using AngularJS is that it no longer pollutes the global scope of the application. Using ng-directive in AngularJS Module, we may add features of an app throughout the whole HTML page. 

    It is possible to extend an AngularJS app's functionality using modules written in AngularJS. Make it simple to repurpose in other contexts. Using Angular support, you may separate different aspects of a problem. 

    How to Create Modules in AngularJS?

    First, let's look at what would happen if we didn't have any modules in our program. Create a file called Firstcontroller.js with code in. Create a function called "FirstController" in our application using the code provided in this section. A basic subtraction is done in the controller above, and the Output is allocated to a new variable called z. A basic HTML page called "demo.html" containing the following code should be created after this step. 

    "Firstcontroller" is included in this code, and the result of $scope c is called using an expression to show it to a user. However, our ng-value app is empty in this case. The syntax is similar to ng-app=". 

    Global access implies that any controllers invoked through ng-app directives will be available to all users. There is no limit to the number of controllers that may be connected. 

    Today's programming favors associating a controller with a module so that a controller may be specified as an entity with its own set of rules. Let's use a module to achieve the same thing. To know more, you can enroll yourself in the professional web development course and grab online web development certificate.

    The Code Explanation: 

    var sampleApp = angular.module('demo',[]); 

    "demo" is built-in Angular to serve as the logical barrier for this module's features. 

    We are connecting the controller to the module through this line. In other words, if we want to use this module's features, we must include a link to this module in the website's main HTML. 

    The Html Code That Forms the Basis of the Page 

    <body ng-app="'Demo'"> 
    <div ng-controller="Firstcontroller"> 
    <h3> Result is:</h3> 
     {{c}} 

    Instead of leaving the ng-app directive blank, provide a reference. Functionality may be specified in the application module. 

    Because Of This, We Discovered: 

    • This module is used to create reusable units of code. 
    • Modules may be loaded in any sequence. 
    • A component can be readily tested. 
    • It is a simple piece of equipment to keep up with. 
    • It becomes much easier when you use a module to structure an application. 

    Types of AngularJS Modules

    AngularJS modules fall into two categories: 

    • Application Modules 
    • Controller Modules 

    Application Modules

    Angular's "angular.module" method may be used to construct an application module. Application modules are treated as global space when creating Angular Modules, including obtaining and registering Angular Js Modules. This technique must be used for all modules in an application, regardless of whether they are Angular base or a third-party module. 

    The "demo" option is used in the code above to refer to an HTML element where the program will be executed. Two arguments are sent via an application module created by the Angular.module(). 

    In the first argument, you must provide the header file supplied in an ng-app directive. The second argument is a list of additional modules reliant on the first one.' We are sending an empty array since there's no dependence. 

    Second, a module declaration that does not include the second parameter (module without []) indicates the use of another module rather than creating an entirely new module. Only the current module is being used to get data. In addition to services and factories, we may construct providers using the module API. For more details, you can choose the KnowledgeHut’s best Angular online course. 

    Controller Modules

    Modules in AngularJS may be used to define controllers in a program. If you are using the ng-controller directive in your application's controller module, you will need to add a controller to your application. 

    Adding Controller to Modules in AngularJS

    Type the following into logic.ts. The employee interface and most of its features are implemented in this class. A class called EmployeeCtrl implements all the attributes of employees. Using the Constructor function, the Employees array attribute header is set to their initial values. The TypeScript code may now be compiled! The tasks have already been added. TypeScript code is generated by invoking the transpiler in the JSON file, which includes the tsc command. 

    To create JavaScript, use Ctrl+Shift+B. The JavaScript code created is shown in the following picture. The EmployeeCtrl function contains all the declarations for the TypeScript class we use in JavaScript, just as we do in JavaScript. 

    The code above demonstrates that the JavaScript function EmployeeCtrl is in the global namespace and is part of IIFE. Angular module's registration controller must be taken into consideration here. To do this, we'll move the registration code to the end of the logic.ts file. Logic.ts After the class code is finished, add the following line to the logic.ts file. Ctrl-Shift-B will update the logic.js file with EmployeeCtrl registered inside the Angular Module as you write your code. 

    We will download the HTTP node package manager to launch the application using the index.html file. To open the command prompt, right-click on index.html, then choose Open in Command-Line. The command prompt will now be open. 

    To Set Up an HTTP Server, Use the Following Command: 

    npm 
    install -g HTTP-server 

    The HTTP server will be set up because of this. You may use it to test and develop on a basic command prompt HTTP server that requires no further setup. 

    Example of Using Controllers with Modules in AngularJS

    A Controller in AngularJS is created by a JavaScript function Object() { [native code] } function that augments the scope of the AngularJS framework. 

    The DOM may be coupled to controllers in a variety of ways. AngularJS will use the provided Controller's function Object() { [native code] } method to invent a fresh Controller object for each of them: 

    The ngController command-line parameter. The $scope injectable argument in the Controller's function Object() { [native code] } method will be used to establish a new child scope. 

    • A controller for a route in the $route specification. 
    • A component directive or an ordinary directive's controller. 
    • The controller object will be allocated to a scope property if the controller is associated using the controller syntax. 

    Use Controllers For 

    Set the $scope object's initial state. 

    Enhance the $scope object's functionality by implementing new methods. 

    Do not use controllers to do any of the following 

    Controllers should only include business logic and not be able to manipulate the DOM. The testability of display logic suffers dramatically when it is placed in Controllers. There are directives for manual DOM manipulation and data binding in AngularJS for most scenarios. To properly format input, AngularJS form controls should be used in their place. 

    Use AngularJS filtering instead of output filters. 

    Use AngularJS services to share code and state across controllers. 

    Manage the other components' lifecycles. 

    Controllers should not attempt to accomplish too many things. For a single view, it should only include the required business logic. 

    If you want to keep controllers small, you may use dependency injection to encapsulate non-controller tasks and then use these services in controllers. The Dependency Injection & Services parts in this tutorial go into detail about this. 

    Adding Directives to Module in AngularJS

    AngularJS uses custom directives to enhance the capabilities of HTML. The "directive" function is used to define custom directives. When a custom directive is active, it simply replaces whatever element in which it is intended. 

    As soon as bootstrap is complete, the AngularJS application uses the custom directive compile() function to perform a one-time action and then processes the element using its link() method depending on its scope. All the following types of items are supported by AngularJS directives. 

    Element directives  

    When a matched element is found, the directive is activated. 

    Attribute  

    When an attribute matching the directive is found, the directive is activated. 

    CSS  

    When a CSS style that matches the directive is found, the directive is activated. 

    Comment  

    When a corresponding remark is found, the directive is activated. 

    Example of Using Directives with Module in AngularJS

    Direct access to the controller's member variable is provided by Angular without the requirement for the scope object in custom directives. As an application grows, you may deal with scope items relating to several controllers. Consequently, the likelihood of obtaining the scope objects of the incorrect controller is considerable. 

    Code  

    A controller named "DemoController" is the first thing we construct. This time, it is attached to the controller rather than the scope object, and the variable "tutorialName" is defined. 

    The term "DemoController" is used in the custom directive to indicate that we wish to utilize the controller. 

    Using the "controllers" argument, we can reference the actual controller itself. As described by Angular, this is how you may use the controller as just a reference point in your app. 

    You may use several controllers in a single directive by providing their blocks, their controller's declarations, and their template statements in the directive. 

    Lastly, in our design, we are using the reference we made in step 3 and the membership variable tied directly to controllers in step 1. You will see the following as Output if you execute your code in a browser and it's a success. 

    Modules and Controllers in File

    laminas-mvc organizes your application-specific code into modules using a module structure. The skeleton's application module in AngularJS supplies bootstrapping, error handling, and routing. To offer application-level controllers for the main page of an application is often used in this tutorial. Still, we will not use the default one supplied in this tutorial since we want the album list to be the leading site. 

    Small HTML pages called "controller files" dynamically start the rendering process for a more extensive HTML page. For the first time, it's possible to make changes that affect the behavior of every page on a website from this point on. 

    Conclusion

    We may deduce from the preceding article that AngularJS modules help clean up the code. Filters, controllers, and directives are separated by defining module in AngularJS in our application's underlying code. We hope you found this explanation helpful. Enroll best Angular online course. 

    Frequently Asked Questions (FAQs)

    1. What is a module file in Angular?

    Components, directives, pipelines, and services associated with an application are collectively referred to as "modules" in Angular. The header, bottom, left, center, and right sections of a website are all part of modules. NgModule can be used to define a module. 

    2. What is module and component in Angular?

     Your Angular applications will run more efficiently if all your modules work together as a single unit. A module's code exports several classes, functions, and values. Your application will comprise several Angular Components, which are the building blocks. 

    3. What are some standard Angular modules?

    NgIf, NgForOf, DecimalPipe, and other fundamental Angular directives & streams are exported. When you build a new app using a new CLI command, the Browser module in AngularJS is included in the root AppModule. 

    4. Can we have multiple modules in AngularJS?

    AngularJS allows you to specify as many modules as you want, as seen below. When using AngularJS, we can easily integrate different modules to create an application that is clear and simple to comprehend. 

    5. Which function is used to create a module in AngularJS?

    This function builds an application or software, where the first argument is an application name that matches the ng-app directive's module in AngularJS name specification. 

    6. How do I register a module in AngularJS?

    An Angular module must first be created using the Angular object module method() before a controller can be registered to it. A controller can then be created in JavaScript by setting up an initial state for the scope object.

    Profile

    Bala Krishna Ragala

    Blog Author

    Bala Krishna Ragala, Head of Engineering at upGrad, is a seasoned writer and captivating storyteller. With a background in EdTech, E-commerce, and LXP, he excels in building B2C and B2B products at scale. With over 15 years of experience in the industry, Bala has held key roles as CTO/Co-Founder at O2Labs and Head of Business (Web Technologies) at Zeolearn LLC. His passion for learning, sharing, and teaching is evident through his extensive training and mentoring endeavors, where he has delivered over 80 online and 50+ onsite trainings. Bala's strengths as a trainer lie in his extensive knowledge of software applications, excellent communication skills, and engaging presentation style.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon