amitabha amitabha - 2 months ago 21
AngularJS Question

Two way databinding in angular js

I am very new in angular js. I am confused what is the 2 way data binding in angularjs. Suppose In my mvc4 application i have bind the model with the view and user changes the value of a textbox which is binded with a model class property.

After clicking the update button, model is passed to the controller with the changed value.Then the value is passed to the database to update the database. i.e. Model is updating with new values.

In my angularjs application I have also binded the same textbox with the model. To update the model user puts a new value to the textbox and model changes. The new model is passed through the web api controller to update the database.

My QUESTION is : What is the difference between this two type of binding mechanism.In both cases view and model is updated. So what is 2 way binding in angularjs. Please help me to clear this concept.

Answer

Two way binding in AngularJS is the synchronization between the view and model (without any need to refresh the page or click a button). Any change in the model is reflected on the view and any change in the view is reflected on the model. Thus, this way of two way binding ensures that your view and model are always updated. Also the controller can remain separate from the view and focus on the model.

This is how you can use two-way binding in AngularJS:

<div ng-app="myApp" ng-controller="myCtrl">
    Name: <input ng-model="name">
    <h1>{{name}}</h1>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.name = "HelloWorld";
});
</script>

MVC makes use of the ASP.NET model binder. It maps the values from an HTML page to a model. When MVC receives an HTTP request, it routes it to a specific action method of a controller. It determines which action method to run based on what is in the route data, then it binds values from the HTTP request to that action method’s parameters. AngularJS handles this differently since the controller is specified in the using the ng-controller tag. Also, you don't need to return a view, the model synchronizes automatically with the view associated in the controller (without the need of return).

You can find some more information on the ASP.NET model binding here: https://docs.asp.net/en/latest/mvc/models/model-binding.html

Comments