I'm currently learning AngularJS and am having difficulty understanding the difference between ng-bind
and ng-model
.
Can anyone tell me how they differ and when one should be used over the other?
ng-bind is also used for data binding but unlike ng-bind it supports only one way data binding.It is used for displaying model properties as innerHTML of html elements such as div and span. This is unlike ng-model which is used for binding input fields and supports two way data binding.
The ng-bind directive tells AngularJS to replace the content of an HTML element with the value of a given variable, or expression. If the value of the given variable, or expression, changes, the content of the specified HTML element will be changed as well.
firstName expression in the application's scope are also reflected instantly in the DOM by Angular. ng-bind is about twice as fast as {{}} expression bind. ng-bind places a watcher on the passed expression and therefore the ng-bind only applies, when the passed value actually changes.
ngModel is a directive which binds input, select and textarea, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during validations in a form.
ng-bind has one-way data binding ($scope --> view). It has a shortcut {{ val }}
which displays the scope value $scope.val
inserted into html where val
is a variable name.
ng-model is intended to be put inside of form elements and has two-way data binding ($scope --> view and view --> $scope) e.g. <input ng-model="val"/>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With