Angular JS – $watch() to handle changes on $scope

With the $watch() method we can trigger an event every time a $scope property changes its value. This is useful when we want to perform a particular tasks when this happen. In this event we want to show the history of all the changes on a particular property.

<div ng-app="myApp">
    <h2>Controller 1</h2>
    <div ng-controller="myController1">
        {{title}}
        <br />
        <input type="text" ng-model="message" />
        <br />
        <br />
        The history is:
        <ul>
            <li ng-repeat="item in history">{{item}}</li>
        </ul>
    </div>
</div>
angular.module("myApp.controllers").controller("myController1", ["$scope", "$rootScope", function ($scope, $rootScope) {
    $scope.title = "This is the controller 1";
    $scope.message = "";
    $scope.history = [];
 
    //The watch() method allow us to handle any change on a $scope
    //property (we can watch the $rootScope as well). Within handler
    //we have both the old and the new value of the property
    $scope.$watch('message', function (newVal, oldVal) {
        $scope.history.push("message changed from '" + oldVal + "' to '" + newVal + "'");
    });
}]);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s