[email protected]      beta
Donate

AngularJs ng-bind directives

Overview: Understanding ng-bind directive, Use of AngularJS ng-bind directives with an example, ng-bind has one-way data binding, ng-bind is better than {{}} in angular.

What is ng-bind directives and its usage?

Angularjs ng-bind directive, by name it self-suggest it is used to bind data to any HTML element. It tells AngularJS to replace the content of an HTML element with the variable, or expression value. The content of HTML element also gets updated whenever the value of given variable or expression changes.

That is if we change the value of the given variable or expression, AngularJS changes the content of the specified HTML element as well.

Directives ng-model , and ng-bind both are used for data binding in AngularJS.

In angularJs ng-model directives is two-way data binding, whereas ng-bind directives is one-way data binding and used for displaying the value inside HTML component as inner HTML.

This directive can not be used for binding with the variable, but only with the HTML elements content. In fact, this can be utilized along with ng-model to bind the component to HTML elements. This directive is very useful for updating the blocks like div, span, etc. with inner HTML content.


Example of using ng-bind directives

Here in this example will display textbox values into our HTML span tag using ng-bind. First, we add a textbox and add ng-model directive with property name as “username”. Next, we place a span tag, with the ng-bind attribute.

The final code looks like as written below.

 <div ng-app>  
 	Enter Name : <input type="text" ng-model="username" /> <br/>
 	<b> Welcome : <span ng-bind="username"> </span> </b> 
 </div>    

Try is yourself

Output:

ng-bind directive simple example

Display textbox value on div using ng-bind.


Using ng-bind is better than {{ }} in AngularJs ?

The answer is yes, ng-bind is better than {{ .... }}, following are some reason why it is good to use ng-bind instead of double curly bracess .

  • User Experience: On page load when AngularJs is bootstrapping, there are chances that for a second user can see double curly braces which placed in the HTML. Though it can solve with ng-cloak but it’s not a good way.

  • Performance: As ng-bind is one-way data binding, and {{ .... }} is two-way data binding. Using ng-bind will reduce the number of watchers in our page. Hence ng-bind will be faster than {{ .... }} double curly braces. So, if we only want to display values and don’t want to reflect its changes to the controller, then using ng-bind directive is good practice. As a result, it will increase the page performance and reduce the page load time.


  Popular Tag
  Recent Posts
  Follow Us
If you find these tutorials helpful then please donate. It will lead me to do more tutorials.
Donate