VOOZH about

URL: https://www.geeksforgeeks.org/angular-js/angularjs-modules/

⇱ AngularJS Modules - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

AngularJS Modules

Last Updated : 21 Feb, 2023

The AngularJS module defines the functionality of the application which is applied on the entire HTML page. It helps to link many components. So it is just a group of related components. It is a container that consists of different parts like controllers, services, and directives.

Note: These modules should be made in normal HTML files like index.html and no need to create a new project in VisualStudio for this section.

Creating a Module in AngularJS:

var app = angular.module("Module-name", []);

In this [], we can add a list of components needed but we are not including any components in this case. This created module is bound with any tag like div, body, etc by adding it to the list of modules.

<div ng-app = "module-name">
 The code in which the module is required.
</div>

Adding a Controller:

app.controller("Controller-name", function($scope) {
 $scope.variable-name= "";
});

Here, we can add any number of variables in the controller and use them in the HTML files, and the body of the tag in which the controller is added to that tag by writing:

 

Module and Controllers in Files: While we can make modules and controllers in the same file along with the HTML file which requires it however we may want to use this module in some other file. Hence this will lead to redundancy so we will prefer to create Module, Controller, and HTML files separately. The Module and Controller are to be stored by using .js files and in order to use them in the HTML file we have to include them in this way:

Example 1: This example illustrates the implementation of the Angular JS Modules.

  • DemoController.js:
  • Module-name: DemoApp.js:
var app = angular.module('DemoApp', []);
  • index.html file:

Output:

👁 Image
 

Note: It makes sure the module and component files are in the same folder otherwise provide the path in which they are saved and run.

Directives in a Module: To add a directive in a module follow the steps:

  • Creating a module as we did earlier:
var app = angular.module("DemoApp", []);
  • Creating a directive:
app.directive("Directive-name", function() {
 return {
 template : "string or some code which is to be executed"
 };
});

Example 2: This is another example illustrating the implementation of the AngularJS Module.

Output:

Welcome to GeeksforGeeks!

Note: Here anything to be printed should not be put in the div which is calling the directive since it gets overwritten by the code in the template.

Comment

Explore