• 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

ngBind, ngBindHtml and ngBindTemplate directives in AngularJS

May 20, 2016 by javainterviewpoint Leave a Comment

ngBind directive

ngBind directive is mostly applied to a span element, it replaces the content of the span with the result of the expression provided. It has the same meaning as the double curly braces {{expression}}.Lets look into the following example of ngBind directive usage.

<!DOCTYPE html>
<html ng-app="bindApp">
<head>
<meta charset="ISO-8859-1">
<title>ngBind Example</title>
<script
 src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js">
</script>
<script>
 angular
    .module("bindApp", [])
    .controller("bindCtrl", function($scope) 
    {
       $scope.printWelcomeMesage = function(username) 
       {
          $scope.welcomeMessage = 'Welcome ' + username + " !!!"
       };
    });
</script>
</head>
<body ng-controller="bindCtrl">
    <strong><span ng-bind="welcomeMessage"></span></strong></br>
    <label>Username Name :</label>
    <input type="text" ng-model="username"></br>
    <button ng-click="printWelcomeMesage(username)">Submit</button>
</body>
</html>

Output : 

ngBind Example

  • In the above code whenever the user enters the value in the text box and hits on the submit button it passes the value of username to our script.  The username value will be passed to our controller through the printWelcomeMessage() method.
  • Once the Angular Script received the username, we are appending the “Welcome” string to it and assign it to scope variables $scope.welcomeMessage
  • Since AngularJS follows two-way binding and we have used the same variable in the UI and as well as the script, the value will be displayed in the expression {{}}

Difference Between {{}} and ngBind directive 

Here comes the question why there is a need for ng-bind directive when there is an alternate available? So lets understand the difference between double curly {{}} and ngBind directive. ngBind is better than {{}} this is because when we use double curly braces {{}} when the page is getting compiled, for a moment the raw expression will be shown to the user. Where as in the case of ng-bind it is not visible to the user as the directive is defined by the attribute of the element. Lets look into the sample code below

<!DOCTYPE html>
<html ng-app="bindApp">
<head>
<meta charset="ISO-8859-1">
<title>double curly ngbind difference</title>
  <script
     src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js">
  </script>
  <script>
    angular
     .module("bindApp", [])
     .controller("bindCtrl", function($scope) 
     {
       $scope.username = "JavaInterviewPoint";
     });
</script>
</head>
<body ng-controller="bindCtrl">
  Double Curly Username : <strong><span>{{username}}</span></strong></br>
 ngBind Username : <strong><span ng-bind="username"></span></strong></br>
</body>
</html>

Usage of ng-cloak directive

When we run the code which has expressions we will be seeing the expresssion {{}}  for a sec and then it disappears. In order to overcome this issue you can use the ngCloak directive to it. The ng-cloak directive actually prevents the document from showing unfinished AngularJS code while AngularJS is being loaded. Hence the above code can be re-written like below

<!DOCTYPE html>
<html ng-app="bindApp">
<head>
<meta charset="ISO-8859-1">
<title>double curly ngbind difference</title>
  <script
     src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js">
  </script>
  <script>
    angular
     .module("bindApp", [])
     .controller("bindCtrl", function($scope) 
     {
       $scope.username = "JavaInterviewPoint";
     });
</script>
</head>
<body ng-controller="bindCtrl">
  Double Curly Username : <strong><span ng-cloak>{{username}}</span></strong></br>
 ngBind Username : <strong><span ng-bind="username"></span></strong></br>
</body>
</html>

ngBindHtml directive

There are times where you may need to bind a string of raw HTML, then we can use the ngBindHtml directive. Usage is similar to that of ngBind directive, however there is a difference between them ngBindHtml directive does not escape the content which will let the browser to interpret the raw HTML code.

<!DOCTYPE html>
<html ng-app="bindApp">
<head>
<meta charset="ISO-8859-1">
<title>ngBind Example</title>
  <script
    src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
  <script
    src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-sanitize.js"></script>
  <script>
  var myapp = angular.module("bindApp",['ngSanitize']);
  myapp.controller("bindCtrl", function($scope) 
  {
    $scope.message = "<h3> Welcome to JavaInterviewPoint !!!</h3>";
  });
  </script>
</head>
<body ng-controller="bindCtrl">
   <strong><span ng-bind-html="message"></span></strong>
</body>
</html>

Output :

ngBindHtml Example

And not like <h3> Welcome to JavaInterviewPoint !!!</h3>, ng-bind-html will let the browser interpret the html.

Note: The ngBindHtml depends upon “angular-sanitize.js” we need to include that in our code and “ngSanitize” in our module dependency

ngBindTemplate directive

The ng-bind-template directive is used to bind multiple expressions to the view. Unlike ng-Bind, the ngBindTemplate can have multiple {{ }} expressions.

<!DOCTYPE html>
<html ng-app="bindTemplateApp">
<head>
<meta charset="ISO-8859-1">
<title>ngBindTemplate Example</title>
 <script
    src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
 <script
    src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-sanitize.js"></script>
 <script>
    var myapp = angular.module("bindTemplateApp",['ngSanitize']);
    myapp.controller("bindTemplateCtrl", function($scope) 
    {
       $scope.customer = { name: "JavaInterviewPoint", country: "India", phone: "1234567890" }; 
    });
 </script>
</head>
<body ng-controller="bindTemplateCtrl">
    <span ng-bind-template="Customer Name : {{ customer.name}} 
                            Customer Country : {{ customer.country }} 
                            Customer Phone : {{ customer.phone }}">
</body>
</html>

Output : 

ngBindTemplate Example

Other interesting articles which you may like …

  • AngularJS Hello World Example
  • AngularJS – Modules and Controllers
  • Two-Way Data Binding in AngularJS Example
  • 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, ngBind, ngBindHtml, ngBindTemplate

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 ·