Menu ▼


ng-model directive in AngularJS

The ng-model directive is used to bind the value to HTML controls and it is responsible for

  • Control validations like required, number, url, email.
  • Registering the control with parent form
  • Maintaining the state of the control like valid, invalid, dirty, touched, untouched
  • Applying related classes on the element like ng-valid, ng-dirty, etc

As AngularJS provides two way binding, The scope property assign to the model will be applied to the control value, and any changes done on the control value will applied to scope property.

Example:
Enter Quantity :
Enter Unit Price :

Quantity : {{Qty}}
Unit Price : {{UnitPrice}}
Total Price : {{Qty*UnitPrice}}

Source code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
</head>
<body>
    <div ng-app="SampleApp" ng-controller="SampleCntrl">
        <table>
            <tr>
                <td>
                    Enter Quantity :
                </td>
                <td>
                    <input type="text" ng-model="Qty" /><br />
                </td>
            </tr>
            <tr>
                <td>
                    Enter Unit Price :
                </td>
                <td>
                    <input type="text" ng-model="UnitPrice" /><br />
                </td>
            </tr>
        </table>
        <br />
        Quantity : {{Qty}}<br />
        Unit Price : {{UnitPrice}}<br />
        Total Price : {{Qty*UnitPrice}}<br />
    </div>
    <script>
        var myapp = angular.module("SampleApp", []);
        myapp.controller("SampleCntrl", function ($scope) {
            $scope.Qty = 5;
            $scope.UnitPrice = 6;
        });
    </script>
</body>
</html>





comments powered by Disqus


Search dotnetlearners.com