Is there any difference between {{ }} and ng-bind in angular.
I am quite new to Angular. I started with using {{ }} and then in the documentation i find ng-bind. I
There is some hint in the official docs: https://docs.angularjs.org/api/ng/directive/ngBind
Typically, you don't use ngBind directly, but instead you use the double curly markup like {{ expression }} which is similar but less verbose.
It is preferable to use ngBind instead of {{ expression }} if a template is momentarily displayed by the browser in its raw state before Angular compiles it. Since ngBind is an element attribute, it makes the bindings invisible to the user while the page is loading.
Another difference is the way ng-bind
and interpolation
display the data.
ng-bind
calls the toString()
method, whereas interpolation
uses a custom "stringify" function.
<div ng-controller="showClockCtrl">
<p>The current time is {{currentDateTime}}.</p>
<p>The current time is <span ng-bind="currentDateTime"></span>.</p>
</div>
<div ng-controller="showClockCtrl">
<p>MyObject is {{myObject}}</p>
<p>MyObject is <span ng-bind="myObject"></span></p>
</div>
<script>
var showClockCtrl = function ($scope) {
$scope.currentDateTime = new Date();
$scope.myObject = {
'key1': 'value1',
'key2': 'value2',
'key3': 'value3'
}
};
</script>
The current time is "2017-11-18T15:09:59.429Z".
The current time is Sat Nov 18 2017 10:09:59 GMT-0500 (EST).
MyObject is {"key1":"value1","key2":"value2","key3":"value3"}
MyObject is [object Object]
In addition to the above mentioned answers,
Performance Issues with Interpolation:
As explained in this thread better,
ng-bind
is a directive and will place a watcher on the passed variable. So the ng-bind
will only apply when the passed value does actually change.
The brackets on the other hand will be dirty checked and refreshed in every $digest, even if it's not necessary.
Not an answer, but ng-bind is easily exchangable by ng-bind-html, which puts actual html text inside the element instead of pure text.
Since I was wondering for (ok, just) minutes, I add it here as well. My problem was, text-DOM explorer shows the same output.
Interpolation is only used for a Read-only purpose and you cannot assign a value to inside the mustache bracket to a variable that has been declared inside the Typescript file.
The basic difference between them is that ng-bind should always be used inside the element <> but Interpolation directive can be used inside, outside and between the elements.
The most obvious difference between them is Flash of Unstyled content while using {{ ... }}
.
However, there is a more subtle difference between the two if the object you pass to {{ obj }}
and ng-bind="obj"
is not a string.
From https://stackoverflow.com/a/19744728/987185 :
Depending on whether you use
{{ ... }}
orng-bind
syntax, the.toJSON
and the.toString
function on your object will be called to determine its representation.