What's the difference between ng-model and ng-bind
Asked Answered
A

8

561

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?

Aholla answered 14/9, 2012 at 7:2 Comment(0)
F
841

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"/>.

Franni answered 14/9, 2012 at 7:44 Comment(9)
Thanks tosh. Would it be a fair assumption to say that ng-bind is only required where the value to display does not require user input. And, ng-modal would be used for values (<input>) that do. The angular documentation seems to suggest this but I'm after a better understanding.Aholla
@Marc Actually ng-bind binds the text content of the element, not its value. Because of this, it can't be used in <input> elements.Molder
@Marc, in that case, just use: <input type="text" value="{{prop}}" />Fabre
@Marc: I find it strange, too. As angular strives to isolate us from HTML quirks, I'd expect it to abstract from such details.Sarcous
A minor update on the topic. The ng-bind directive could be emulated with {{::val}} in order to achieve one-way data binding. That is very helpful when reducing the number of watchers.Brashy
@JakubBarczyk {{::va}} is one time binding and not one way.Reckless
@Wachburn It's one-way but more important it's one-time. It stops watching model changes after model takes any value. So it can't be used as one-way binding if we need regular one-way binding.Floro
so what is the difference between ng-bind and {{}} ?Robin
@ANinJa, please check differences here.. #25742086Everything
R
142

tosh's answer gets to the heart of the question nicely. Here's some additional information....

Filters & Formatters

ng-bind and ng-model both have the concept of transforming data before outputting it for the user. To that end, ng-bind uses filters, while ng-model uses formatters.

filter (ng-bind)

With ng-bind, you can use a filter to transform your data. For example,

<div ng-bind="mystring | uppercase"></div>,

or more simply:

<div>{{mystring | uppercase}}</div>

Note that uppercase is a built-in angular filter, although you can also build your own filter.

formatter (ng-model)

To create an ng-model formatter, you create a directive that does require: 'ngModel', which allows that directive to gain access to ngModel's controller. For example:

app.directive('myModelFormatter', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, controller) {
     controller.$formatters.push(function(value) {
        return value.toUpperCase();
      });
    }
  }
}

Then in your partial:

<input ngModel="mystring" my-model-formatter />

This is essentially the ng-model equivalent of what the uppercase filter is doing in the ng-bind example above.


Parsers

Now, what if you plan to allow the user to change the value of mystring? ng-bind only has one way binding, from model-->view. However, ng-model can bind from view-->model which means that you may allow the user to change the model's data, and using a parser you can format the user's data in a streamlined manner. Here's what that looks like:

app.directive('myModelFormatter', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, controller) {
     controller.$parsers.push(function(value) {
        return value.toLowerCase();
      });
    }
  }
}

Play with a live plunker of the ng-model formatter/parser examples


What Else?

ng-model also has built-in validation. Simply modify your $parsers or $formatters function to call ngModel's controller.$setValidity(validationErrorKey, isValid) function.

Angular 1.3 has a new $validators array which you can use for validation instead of $parsers or $formatters.

Angular 1.3 also has getter/setter support for ngModel

Rising answered 20/5, 2014 at 2:52 Comment(1)
+ 1. Thanks for the extra info. Its always good/great to have a quick answer (Tosh's) and then a detailed WHY & HOW answer like yours to learn/understand the more in reasoning/use cases.Pompidou
P
30

ngModel

The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope.

This directive executes at priority level 1.

Example Plunker

JAVASCRIPT

angular.module('inputExample', [])
   .controller('ExampleController', ['$scope', function($scope) {
     $scope.val = '1';
}]);

CSS

.my-input {
    -webkit-transition:all linear 0.5s;
    transition:all linear 0.5s;
    background: transparent;
}
.my-input.ng-invalid {
    color:white;
    background: red;
}

HTML

<p id="inputDescription">
   Update input to see transitions when valid/invalid.
   Integer is a valid value.
</p>
<form name="testForm" ng-controller="ExampleController">
    <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
         aria-describedby="inputDescription" />
</form>

ngModel is responsible for:

  • Binding the view into the model, which other directives such as input, textarea or select require.
  • Providing validation behavior (i.e. required, number, email, url).
  • Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  • Setting related css classes on the element (ng-valid, ng-invalid, ng-dirty, ng-pristine, ng-touched, ng-untouched) including animations.
  • Registering the control with its parent form.

ngBind

The ngBind attribute tells Angular to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.

This directive executes at priority level 0.

Example Plunker

JAVASCRIPT

angular.module('bindExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
    $scope.name = 'Whirled';
}]);

HTML

<div ng-controller="ExampleController">
  <label>Enter name: <input type="text" ng-model="name"></label><br>
  Hello <span ng-bind="name"></span>!
</div>

ngBind is responsible for:

  • Replacing the text content of the specified HTML element with the value of a given expression.
Pita answered 17/4, 2015 at 12:25 Comment(1)
Although I appreciate this thorough response, my previously selected answer will remain as it provided just enough information to understand the difference.Aholla
G
10

If you are hesitating between using ng-bind or ng-model, try to answer these questions:


Do you only need to display data?

  • Yes: ng-bind (one-way binding)

  • No: ng-model (two-way binding)

Do you need to bind text content (and not value)?

  • Yes: ng-bind

  • No: ng-model (you should not use ng-bind where value is required)

Is your tag a HTML <input>?

  • Yes: ng-model (you cannot use ng-bind with <input> tag)

  • No: ng-bind

Gadid answered 16/11, 2016 at 9:22 Comment(0)
A
6

ng-model

ng-model directive in AngularJS is one of the greatest strength to bind the variables used in application with input components. This works as two way data binding. If you want to understand better about the two way bindings, you have an input component and the value updated into that field must be reflected in other part of the application. The better solution is to bind a variable to that field and output that variable whereever you wish to display the updated value throughoput the application.

ng-bind

ng-bind works much different than ng-model. ng-bind is one way data binding 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. Infact this can be used 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.

This example would help you to understand.

Abdias answered 29/4, 2015 at 0:21 Comment(0)
I
5

angular.module('testApp',[]).controller('testCTRL',function($scope)
                               
{
  
$scope.testingModel = "This is ModelData.If you change textbox data it will reflected here..because model is two way binding reflected in both.";
$scope.testingBind = "This is BindData.You can't change this beacause it is binded with html..In above textBox i tried to use bind, but it is not working because it is one way binding.";            
});
div input{
width:600px;  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<head>Diff b/w model and bind</head>
<body data-ng-app="testApp">
    <div data-ng-controller="testCTRL">
        Model-Data : <input type="text" data-ng-model="testingModel">
        <p>{{testingModel}}</p>
          <input type="text" data-ng-bind="testingBind">
          <p ng-bind="testingBind"></p>
    </div>
</body>
Intervalometer answered 9/12, 2014 at 15:9 Comment(0)
P
3

ngModel usually use for input tags for bind a variable that we can change variable from controller and html page but ngBind use for display a variable in html page and we can change variable just from controller and html just show variable.

Paintbox answered 29/12, 2016 at 13:19 Comment(0)
R
1

We can use ng-bind with <p> to display, we can use shortcut for ng-bind {{model}}, we cannot use ng-bind with html input controls, but we can use shortcut for ng-bind {{model}} with html input controls.

<input type="text" ng-model="name" placeholder="Enter Something"/>
<input type="text" value="{{name}}" placeholder="Enter Something"/>
  Hello {{name}}
<p ng-bind="name"</p>
Roughandtumble answered 7/3, 2017 at 13:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.