angularjs - How can i remove the watches one by one when i fire watch on element for multiple times? -
i fire watch multiple times on input field clicking on start watch. , want remove watches 1 one on present on input field. how can it?
(function(angular) { 'use strict'; angular.module('docsbindexample', []) .controller('controller', ['$scope', function($scope) { $scope.name = 'max karl ernst ludwig planck (april 23, 1858 – october 4, 1947)'; $scope.test = ""; $scope.cntr = 0; /* jscode igonore other methods*/ $scope.initwatch = function() { $scope.$watch('test', function(newvalue, oldvalue) { if (newvalue !== oldvalue) $scope.cntr++; }); }; }]); })(window.angular);
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>example - example-directive-bind-production</title> <script src="//code.angularjs.org/snapshot/angular.min.js"></script> <script src="script.js"></script> </head> <body ng-app="docsbindexample"> <!--html code--> <div ng-controller="controller"> <input type="text" ng-model="test" /> <input type="button" value="start watch" ng-click="initwatch()" /> <!-- watch called multiple times clicking it--> <br/> watch counter: {{cntr}} <!-- count displayed here --> </div> </body> </html> <!-- copyright 2017 google inc. rights reserved. use of source code governed mit-style license can found in license file @ http://angular.io/license --> <!-- if version <named framework> [gte 2.0] --> content relevant named framework versions 2.0 , greater. <!-- end version if -->
instead of using watcher, use ng-change directive:
<input type="text" ng-model="test" ng-change="watch()"/> <input type="button" value="enable watch" ng-click="enablewatch()" />
instead of adding , removing watcher, use enable
flag:
$scope.enablewatch = function() { $scope.enable = ! $scope.enable; }; $scope.watch = function() { if ($scope.enable) { $scope.cntr++; }; };
the technique of adding , removing watchers creates implicit state difficult see , difficult debug. technique should avoided. instead adding flag creates state readily visible , debugged. follows design principle of separation of concerns model separated view , watchers.
the demo
angular.module('docsbindexample', []) .controller('controller', ['$scope', function($scope) { $scope.name = 'max karl ernst ludwig planck (april 23, 1858 – october 4, 1947)'; $scope.test = ""; $scope.cntr = 0; /* jscode igonore other methods*/ $scope.enablewatch = function() { $scope.enable = ! $scope.enable; }; $scope.watch = function() { if ($scope.enable) { $scope.cntr++; }; }; }]);
<script src="//unpkg.com/angular/angular.js"></script> <body ng-app="docsbindexample"> <!--html code--> <div ng-controller="controller"> <input type="text" ng-model="test" ng-change="watch()"/> <input type="button" value="enable watch" ng-click="enablewatch()" /> <br/> <p ng-show="enable">watch enabled</p> watch counter: {{cntr}} </div> </body>
Comments
Post a Comment