AngularJS $watch function

Updated on     Kisan Patel

AngularJS Scope.$watch function can be used to react on a model change to trigger some further actions.

The $watch function itself takes two required arguments and a third optional one:

angular.module("myApp")
   .controller("MyController", ['$scope', function($scope) {
         $scope.$watch('full_name', function(newVal, oldVal, scope) {
             // the newVal of the full_name will be available here
             // while the oldVal is the old value of full_name
         });
   }]);

Example

<div ng-app="app" ng-controller="simpleController">
   <input type="text" ng-model="name" placeholder="Your name">
   <p>{{ greeting }}</p>
</div>
<script type="text/javascript">
  var myApp = angular.module('app', []);
 
  myApp.controller("simpleController", ['$scope', function($scope){
      $scope.name = "";
 
      $scope.$watch("name", function(newValue, oldValue) {
            if ($scope.name.length > 0) {
                $scope.greeting = $scope.name + ", How are you?";
            }
      });
  }]);
</script>

Here, In our example we use the text input value to print a friendly greeting message.

Here, we have also set up a $watch listener on the name property and detect any changes to the value.

watch-demo

 


AngularJS

Leave a Reply