AngularJS Tutorial - Respond to Scope Changes








The following code shows how to respond to Scope Changes.

Example

To react on a model change to trigger some further actions, use the $watch function in your controller.


<!--   w w  w  .j a v a2  s  .c om-->

<!doctype html>
<html ng-app>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
    <script>
function MyCtrl($scope) {
  $scope.name = "";

  $scope.$watch("name", function(newValue, oldValue) {
    if (newValue.length > 0) {
      $scope.greeting = "input: " + newValue;
    }
  });
}    
    </script>
  </head>
  <body ng-app>
    <div ng-controller="MyCtrl">
      <input type="text" ng-model="name" placeholder="Enter your name">
      <p>{{greeting}}</p>
    </div>
  </body>
</html>

The code above is rendered as follows: