blog

Home / DeveloperSection / Blogs / Data Binding in AngularJS

Data Binding in AngularJS

Data Binding in AngularJS

Ravi Vishwakarma 60 24-Jun-2024

Data Binding is one of the most powerful and commonly used features in AngularJS. It provides a way to synchronize the data between the model and the view. This means that when the data in the model changes, the view reflects that change, and vice versa.

There are two main types of data binding in AngularJS:

  1. One-Way Data Binding
  2. Two-Way Data Binding

 

One-Way Data Binding

In one-way data binding, the data flows in one direction, either from the model to the view or from the view to the model. This is useful when you only need to display data without updating the model from the view.

Model to View: Updates the view whenever the model changes.

<div ng-app="myApp" ng-controller="myCtrl">
    <p>{{ message }}</p>
    <p ng-bind="message"></p>
</div>

View to Model: Updates the model when the view changes, usually through user input.

<div ng-app="myApp" ng-controller="myCtrl">
    <input type="text" ng-model="message">
</div>

Two-Way Data Binding

In two-way data binding, the data flows in both directions. Changes in the model update the view, and changes in the view update the model. This is achieved using the ng-model directive.

<div ng-app="myApp" ng-controller="myCtrl">
    <input type="text" ng-model="message">
    <p>{{ message }}</p>
</div>

Example -

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    <script>
        // Define the module
        var app = angular.module('myApp', []);

        // Define the controller
        app.controller('myCtrl', function($scope) {
            $scope.message = 'Hello, AngularJS!';
            $scope.updateMessage = function(newMessage) {
                $scope.message = newMessage;
            };
        });
    </script>
</head>
<body ng-app="myApp">

    <div ng-controller="myCtrl">
        <h2>One-Way Data Binding</h2>
        <p>{{ message }}</p>
        <p ng-bind="message"></p>

        <h2>Two-Way Data Binding</h2>
        <input type="text" ng-model="message">
        <p>{{ message }}</p>

        <h2>Updating Model from View</h2>
        <input type="text" ng-model="newMessage">
        <button ng-click="updateMessage(newMessage)">Update Message</button>
    </div>

</body>
</html>

 


Hi, my self Ravi Vishwakarma. I have completed my studies at SPICBB Varanasi. now I completed MCA with 76% form Veer Bahadur Singh Purvanchal University Jaunpur. SWE @ MindStick | Software Engineer | Web Developer | .Net Developer | Web Developer | Backend Engineer | .NET Core Developer

Leave Comment

Comments

Liked By