Open In App

How to Detect Change in Model Automatically in AngularJS ?

Last Updated : 21 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Change detection is a crucial aspect of maintaining the integrity and performance of AngularJS applications. It ensures that the user interface reflects the latest data and that updates are efficiently propagated throughout the application. In this article, we will explore how to detect changes in models automatically using AngularJS.

AngularJS provides a built-in mechanism for change detection through the “$watch” function. This function allows you to monitor changes in a specific model or expression and execute custom logic when a change is detected.

Syntax:

$scope.$watch('model', function(newValue, oldValue) {
    // Custom logic to handle the change
});

 

Parameters: The “$watch” function takes two parameters:

  • model: The model or expression to watch, and a callback function that will be executed when a change is detected.
  • Callback: The callback function receives the new and old values of the model or expression.

Approach 1: In this approach, we have an AngularJS application with a controller named myController. Inside the controller, we define a $watch function to monitor changes in the message model. When a change is detected, the callback function is executed, logging the updated value to the console. The HTML markup includes an <input> element with the ng-model directive, which binds the input value to the message model. Any changes made to the input field will be reflected in the message model. Additionally, the example demonstrates an optional part where we programmatically update the message model after a delay using setTimeout() and the $apply() function. This showcases how changes triggered outside of user interactions can also be detected by the $watch function.

Example 1: This is the basic example that demonstrates how you can automatically detect changes in a model by providing the input to the input field.

HTML




<!DOCTYPE html5>
<html lang="en" 
      ng-app="myApp">
  
<head>
    <meta charset="UTF-8">
    <title>
          Automatic Change Detection in AngularJS
      </title>
    <script src=
      </script>
    <script>
        
        // Define the AngularJS application module
        var app = angular.module('myApp', []);
  
        // Define the AngularJS controller
        app.controller('myController', function ($scope) {
            $scope.message = 'Initial message';
  
            // Watch for changes in the model
            $scope.$watch('message', function (newValue, oldValue) {
                if (newValue !== oldValue) {
                    console.log('Message updated:', newValue);
                }
            });
        });
    </script>
</head>
  
<body ng-controller="myController">
    <h1 style="color:green">
          GeeksforGeeks
      </h1>
    <h3>
          How to detect change in model automatically?
      </h3>
    <h4 style="color:green">{{ message }}</h4>
    <input type="text" ng-model="message">
  
    <script>
        
        // Optional: Update the model programmatically after a delay
        setTimeout(function () {
            var scope = 
                angular.element(document.getElementById('myApp')).scope();
            scope.$apply(function () {
                scope.message = 'Updated message';
            });
        }, 3000);
    </script>
</body>
  
</html>


Output:

ezgifcom-video-to-gif-(5).gif

Approach 2: In this approach, we have an AngularJS application with a controller named myController. The controller defines a $watch function to monitor changes in the counter model. Whenever the value of the counter changes, the callback function is executed, logging the updated value to the console. Inside the controller, we also have a setInterval function that increments the counter model every second. The use of $apply is necessary in this case to ensure that AngularJS is aware of the change and triggers the corresponding $watch function. The HTML markup simply displays the value of the counter model using the {{ counter }} expression.

Example: This example demonstrates how you can automatically detect changes in a model that are not directly tied to user interactions, such as the incrementing of the counter in this case.

HTML




<!DOCTYPE html>
<html lang="en" 
      ng-app="myApp">
  
<head>
    <meta charset="UTF-8">
    <title>
          Automatic Change Detection in AngularJS
      </title>
    <script src=
    </script>
    <script>
          
        // Define the AngularJS application module
        var app = angular.module('myApp', []);
  
        // Define the AngularJS controller
        app.controller('myController', function ($scope) {
            $scope.counter = 0;
  
            // Watch for changes in the model
            $scope.$watch('counter', function (newValue, oldValue) {
                if (newValue !== oldValue) {
                    console.log('Counter updated:', newValue);
                }
            });
  
            // Increment the counter every second
            setInterval(function () {
                $scope.$apply(function () {
                    $scope.counter++;
                });
            }, 1000);
        });
    </script>
</head>
  
<body ng-controller="myController">
    <h1 style="color:green">
        Counter: {{ counter }}
    </h1>
</body>
  
</html>


Output:

ezgifcom-video-to-gif-(6).gif



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads