AngularJS - watch changes in model

by Krzysztof Safjanowski

HTML

<div ng-app="change">
    <div ng-controller="change-monitor">
        toBeChanged: {{ toBeChanged }} <br />
        <input type="text" ng-model="toBeChanged" change-monitor="toBeChanged" />
        
        <button ng-click="setValue()">Set Value</button>
    </div>
</div>

JavaScript

angular.module('change', [])
.controller('change-monitor', function($scope){
    $scope.setValue = function() {
        $scope.toBeChanged = 'new value';
    };
})
.directive('changeMonitor', function() {
    return {
        require: '?ngModel',
        restrict: 'A',
        link: function(scope, element, attrs, ngModel) {
            scope.$watch(attrs.ngModel, function() {
                console.log('something was changed');
            });
        }
    };
});