AngularJS $scope.$watch

js:

var app = angular.module('app', []);
 
app.controller('appController', function ($scope) {
    $scope.value = 'change this default input value';
    $scope.counter = 0;
 
    $scope.$watch('value',
    function (newValue, oldValue) { // change handler
        if (newValue !== oldValue) {
            $scope.counter = $scope.counter + 1; // only increment the counter if the value changed
        }
    });
});

html:

<section ng-app="app">
    <article ng-controller="appController">
        <h1>Change input value</h1>
        <p>
            <input type="text" ng-model="value" />
        </p>
        <p>value = "{{value}}"</p>
        <p>counter (will change if value will change) = {{counter}}</p>
    </article>
</section>

Leave a Reply

Your email address will not be published. Required fields are marked *