• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

AngularJS – Modules and Controllers

April 20, 2016 by javainterviewpoint Leave a Comment

AngularJS Modules

Modules are the AngularJS way of packaging similar functional codes under a single name. In simple terms it is like package of Java. AngularJS Modules consist of two main parts.

  • An AngularJS module can define its own Controllers, Services, factories and directives.These can be access through out the module.
  • Second part is it can have its own dependencies, when dependencies are defined then AngularJS will go find the module with particular name and make sure their controllers,services,factories and directives are available to this module.

Suppose if we want to declare a module for our application “HelloApp”, this is how we need to define it

var myApp = angular.module('HelloApp',[]);
  1. The first argument is the name of the AngularJS modules in our case it is “HelloApp”
  2. The Second argument [] , is an array of other angular modules which this module depend on. In our case we dont depend on any other modules.

In order to define the depenedencies simply add their module name in the array seperated by comma. Suppose our “HelloApp” is depending on two other modules “WelcomeApp” and “GreetingApp”, then we can add dependencies like below

angular.module('HelloApp',['WelcomeApp','GreetingApp']);

AngularJS Controller

AngularJS Controllers is the place wherein which we will be writing all our business logic such as fetching data from the server and sending it to the UI, Event handling mechanisms, deciding which block to show, etc.. all these and more happens within the controllers.

We can register a controller with our angular module using the controller function provided by modules. The AngularJS controller has two main parts they are

  1. The first parameter is a string that specifies the controller name, in our case we naming our controller as “HelloCtrl”
  2. The second argument is the actual controller definition. We can inject $scope as a parameter to our controller with which we can pass values to and fro to our view.

A controller can be define like below

var myApp = angular.module('HelloApp',[]);
myApp.controller('HelloCtrl', function ($scope){

});

Now lets take our AngularJS HelloWorld Example and add Module & Controller to it.

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>HelloWorld Application</title>
<script
 src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js">
 
</script>
</head>
   <body ng-app="myApp">
      <div ng-controller="HelloCtrl">
         <form>
           <input type="text" ng-model="username" placeholder="Enter your name">
           <button ng-click="updateUserMessage(username)" type="button">Update Message</button>
         </form>
         <script type="text/javascript">
            angular.module('myApp', [])
            .controller('HelloCtrl',function($scope) 
            {
                $scope.message = '';
                $scope.updateUserMessage = function(username)
                {
                    $scope.message = "Welcome "+username+"!!!" 
                };
            });
         </script>
       <h2>{{message}}</h2>
     </div>
   </body>
</html>

Output

AngularJS Controller Example

 

 

 

How everything works ?

    • The ng-app directive is added to the <body> tag. ng-app defines the starting point of the angularjs application flow. Here our application name is “myApp”, which will be used in the module of our angular application.
    • We have created controller “HelloCtrl” using ng-controller directive. All the business logic will be performed here.
    • Within the <form> tag, We have an input tag, which is associated with the ng-model “username”. Here AngularJS stores the value entered by the user in the text field to the variable “username” which is mentioned in the ng-model.
    • Once the user clicks on the “Update Message” button, updateUserMessage() method will be called, passing the username to Angular Script.
    • Once the Angular Script received the username, we are appending the username with the welcome message and assigning it to the variable $scope.message.
    • The Welcome message along with the username will be displayed in the UI. Since AngularJS follows two-way binding and we have used the same variable in the UI and as well as the script.

Working with Multi Controllers

There will times where you may need to create more than one controller on a single angular module. It possible in angularjs. For example lets create two controller one for addition and one for subtraction.

<!DOCTYPE html>
<html>
<head>
  <meta charset="ISO-8859-1">
  <title>Angular Calculator</title>
  <script
     src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js">
   </script>
</head>
<body ng-app="CalcApp">
   <div ng-controller="AddCtrl">
       <h3>Addition</h3>
       <p>
         <label>Value for A:</label> <input type="number" id="a" ng-model="a">
       </p>
       <p>
          <label>Value for B:</label> <input type="number" id="b" ng-model="b">
       </p>
       <p>
           <button ng-click="add(a,b)">Add</button>
           Result: {{ result }}
        </p>
    </div>
 
    <div ng-controller="SubCtrl">
       <h3>Subtraction</h3>
 
       <p>
           <label>Value for A:</label> <input type="number" id="a" ng-model="a">
       </p>
       <p>
            <label>Value for B:</label> <input type="number" id="b" ng-model="b">
        </p>
        <p>
            <button ng-click="subtract(a,b)">Subtract</button>
             Result: {{ result }}
         </p>
      </div>
 
   <script type="text/javascript">
       var myApp = angular.module('CalcApp', []);

        myApp.controller('AddCtrl', function($scope) {
           $scope.result = 0;

           $scope.add = function(a, b) {
               $scope.result = a + b;
           };
        });
 
        myApp.controller('SubCtrl', function($scope) {
           $scope.result = 0;

           $scope.subtract = function(a, b) {
              $scope.result = a - b;
           };
       });
    </script>
</body>
</html>

We have created two controllers, AddCtrl and SubCtrl for performing the add and subtraction operation respectively. Upon clicking the Add button, the ng-click calls the add() method of the Controller1 (AddCtrl) and display the result on {{ result }} . Same thing happens for the Subtraction operation as well, it calls the SubCtrl

Output :

Hit on the URL

http://localhost:8080/AngularJS_Tutorial/AngularCalculator.html

AngularJS Controllers Example

Other interesting articles which you may like …

  • AngularJS Hello World Example
  • Two-Way Data Binding in AngularJS Example
  • ngBind, ngBindHtml and ngBindTemplate
  • AngularJS Form Validation with ngMessages
  • AngularJS Routing Example using ngRoute
  • AngularJS Spring MVC integration
  • AngularJS Spring MVC CRUD Example using $http service

Filed Under: AngularJS, J2EE, Java Tagged With: AngularJS, Controllers, Modules

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·