AngularJS > Events

ng-change events in AngularJS

How to perform on change event operations in AngularJS?


To perform change event operations in AngularJS, we use ng-change directive.

In below <script> block, we have declared 3 functions each for change event of CheckBox, TextBox and DropDown respectively. When these events executes, respective $scope properties values are set and its value is written on the web page in HTML block.

<script>
    var app = angular.module("app", []);
    app.controller("ChangeController", function ($scope) {

        $scope.CheckBoxChanged = function () {
            $scope.CheckBoxStatus = $scope.chkValue;
        };

        $scope.TextBoxChanged = function () {
            $scope.TextBoxStatus = $scope.txtValue;
        };

        $scope.DropDownChnaged = function () {
            $scope.DropDownStatus = $scope.dropValue;
        };

    });
</script>

<div ng-app="app" ng-controller="ChangeController">
    <input type="checkbox" name="chk1" ng-model="chkValue" ng-change="CheckBoxChanged()" />
    <p>Check box status: {{ CheckBoxStatus }}</p>
    
    <hr />
    <input type="text" name="txt1" ng-model="txtValue" ng-change="TextBoxChanged()" />
    <p>Text box status: {{ TextBoxStatus }}</p>

    <select name="dropChange" ng-model="dropValue" ng-change="DropDownChnaged()">
        <option value="M">Male</option>
        <option value="F">Female</option>
    </select>
    <p>Dropdown box status: {{ DropDownStatus }}</p>
</div>

In the HTML block, for each input element (check box, text box and drop down), we have a ng-model directive that holds current value of the element. Notice the ng-change directive where we have specified the function name to execute.

When user changes the value of these elements, corresponding function executes and changes the value of the model and ultimately its value is set to the $scope properties that gets written on the page in the paragraph just below that element.

Change events in AngularJS

 Views: 71981 | Post Order: 41




Write for us






Hosting Recommendations