AngularJS: Watch for data change using directive

Hi Guys,

In order to watch any change in model you can use below code to find this.

Here directive "is-change" tracks if there is any modification in the data model.
<input type="text" is-change ng-model="data"/>

Directive "is-change" uses $watch to track any modification in model
scope.$watch('val', function(newValue, oldValue) {
                if (newValue)
                    console.log("New value: " + scope.val);
            }, true);

You can find implementation code below.
index.html
<html ng-app="simpleDirective">
<head>
<link rel="stylesheet" href="stylesheet.css"/>
<script src="angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="Controller"> 
  <input type="text" is-change ng-model="data"/>
</div>
</body>
</html>
app.js
var app = angular.module('simpleDirective', []);

app.controller('Controller', ['$scope', function($scope) {
 $scope.data = "Hello";
}]);

app.directive("isChange", function(){
 return {
  restrict : "A",
  scope: {
            val: '=ngModel'
        },
        link: function(scope, element, attrs) {
            scope.$watch('val', function(newValue, oldValue) {
                if (newValue)
                    console.log("New value: " + scope.val);
            }, true);
        }
 }
});


Good day :)

Post a Comment

0 Comments