Reputation: 3760
What is the difference in AngularJS data-binding when binding a model to an input
vs binding a model with a non-input
element (e.g. div)?
Upvotes: 1
Views: 1011
Reputation: 1726
Angular has special directive which enables two way data binding for input elements ng-model
, then it has also two way but in practice it behaves as one way binding ng-bind
or shorthand {{expresion}}
, then again it has a proper one time binding using {{::expresion}}
when you are sure you only want to display initial data which will not be updated by any other proces later. So if you want to mutate your model using inputs go for ng-model
.
Upvotes: -1
Reputation: 11548
The non input type elements are intended to use ng-bind which provides one way binding but input types use ng-model to provide 2 way binding.
If you want 2 way binding on a non input but editable (html5) element you will have to implement that yourself for such elements to support ng-model.
example of adding support for ng-model to non input element is:
app.directive("contenteditable", function() {
return {
restrict: "A",
require: "ngModel",
link: function(scope, element, attrs, ngModel) {
function read() {
ngModel.$setViewValue(element.html());
}
ngModel.$render = function() {
element.html(ngModel.$viewValue || "");
};
element.bind("blur keyup change", function() {
scope.$apply(read);
});
}
};
});
And finally let's not forget the third option angular offers which is a "One time" or one off binding. which happens only once if you don't need the binded element to keep updating after it's first initial value from the scope:
<p>Hello {{::name}}!</p>
<custom-directive two-way-attribute="::oneWayExpression"></custom-directive>
Source: http://blog.thoughtram.io/angularjs/2014/10/14/exploring-angular-1.3-one-time-bindings.html
Upvotes: 4