Tuesday, 22 August 2017

Difference between {{}} and ng-bind in AngularJS

To bind our data to the HTML page, Angular gives the ability to use {{}} known as double curly brackets or ng-bind.Both ways are performing the same functionality.


{{}}

Example:-      Double Curly brackets in Angular JS

name is JS object or some variable we are referring to.
It makes your template very readable i.e Anyone going through a code such as {{ name }} can easily understand that "name"  is a variable bounded to the DOM.

Drawbacks of {{}}

Sometimes when we  load our application in the browser , we can notice flashing content for some milliseconds before {{ name }} is resolved and data is loaded.
flashing-content
Flashing content
This happens because the template is loaded before AngularJS had a chance to go in and compile the elements. To resolve this issue, you can use ng-cloak directive.

ng-bind is used inside an HTML DOM element:

Example:-
ng-bind

We are using the same expression which we used for double curly brackets.

The major difference between ng-bind and {{}} is that ng-bind creates a watcher for variable passed to it(i.e. name as in above example), while curly brackets({{}}) will (store the entire expression in memory i.e. }perform dirty-checking and refreshing the expression in every digest cycle even if it is not required.

ng-bind will only apply when the value passed is changing actually.

In the first approach(i.e. {{}}), AngularJS evaluates the expression then replaces it with some value which sometime be left with the flashing double curly brackets but ng-bind saves this time by informing AngularJS to put the contents of the expression within the element itself.
Note:-

  • {{}} sometimes cause performance issue if we have thousand of bindings in our page.In these scenario's, we should go with ng-bind.
  • For some modules, like translate module is implemented  or having binding which are not going to change , make the practice to use :: (double colon) before our binding. Example

4 comments:

  1. nemco.com.au
    Angularjs Development Services | AngularJS Development Company
    Nemco is a top level AngularJS Development Company based in sydney, Australia. provide AngularJS development service. Hire angularjs developers from Nemco.
    angularjs development| angularjs development company

    ReplyDelete
  2. Neo Thermal Insulation is one of the leading air bubble insulation manufacturers in India. We have a concept of energy conservation to reduce global warming.

    ReplyDelete
  3. Appreciate you sharing, great article .Much thanks again. Really Cool.
    data science training
    python training
    angular js training

    ReplyDelete