Using AngularJS Modules, you can control functionalities and behavior if AngularJS application with the help of Controllers and Directives.
These terms may be create curiosity at this moment which is really important but we’ll cover controllers and directives in other blogs.
Let’s have a look on Modules as of now.
Modules are used to define the application. Remember AngularJS application starts form the HTML tag having AngularJS directive ng-app. This is container for different part of the application and application controllers. AngularJS controllers are always dependent of AngularJS Modules.
We’ll learn following lessons in this blog:
- Create a new Module
- Using Controller with Module
- Using Directives with Module
- Modules and Controllers in separate JS files
Create a new Module
Here ‘angularJSApp’ variable associated with a HTML element refers to AngularJS application with the help of directive ng-app. We can define a module using an API as shown in the code above.
var app = angular.module(“angularJSApp”,);
This variable ‘app’ can be used further to work with different parts of angularJS application.
Using Controller with Module
After creating a reference to module, we can work with inner variables in AngularJS application. In the above example, we can see that we are setting ‘firstName’ and ‘lastName’ variables using AngularJS Controller which is always dependent on module.
Using Directives with Module
We can also create custom directives in AngularJS. In the above example, a custom directive ‘sm-directive-test’ is implemented. its output is provided below:
Let’s see another example:
In this case, we can see that AngularJS HTML element
has inner Text and anonymous constructor of custom directive has one statement as alert(‘Hi’). Let’s see the behavior of AngularJS in this case.As soon as we run your application, we will see output web page as Image ‘directive1’. Inner text is being displayed and alert message is also being shown.
When we click OK on alert message. Web page will be changed to Image ‘directive2’ i.e. output is overridden by return statement in directive constructor.
Modules and Controllers in separate JS files