Rushikesh Joshi
Rushikesh Joshi

Reputation: 1

One-Way or One-Time binding in Angular and Watchers

I have a question about how to avoid watchers when you have readonly input textbox in AngularJS.

I have created plunker for it : plunker link : OneWay Binding using ng-value

This shows that even when I am using ng-value for readonly input text, still a watcher has been added for it.

I simple want to avoid watchers when there are readonly controls, I am asking this because in my enterprise application, even for readonly page I have more-than 200 readonly controls and watcher count there is coming around 1100 which is slowing down my Angular Application.

Upvotes: 0

Views: 1124

Answers (1)

Sámal Rasmussen
Sámal Rasmussen

Reputation: 3515

Found a way to do it with one way bindings:

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  
//$scope.watcherCount = 0;
$scope.countWatchers = function () {
    var root = angular.element(document).injector().get('$rootScope');
    var count = root.$$watchers ? root.$$watchers.length : 0; // include the current scope
    var pendingChildHeads = [root.$$childHead];
    var currentScope;
    
    while (pendingChildHeads.length) {
        currentScope = pendingChildHeads.shift();

        while (currentScope) {
            count += currentScope.$$watchers ? currentScope.$$watchers.length : 0;
            pendingChildHeads.push(currentScope.$$childHead);
            currentScope = currentScope.$$nextSibling;
        }
    }

    $scope.watcherCount = count;
    
    // alert("there are " + count  + " watchers");
    return count;
  }
});
<!DOCTYPE html>
<html ng-app="app">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <input type="text" ng-model="a">
    <input type="text" value="{{::a}}" ng-readonly=true></input>
    <button ng-click="countWatchers()">Get Watchers</button>
    <br>
    Watcher Count <!--table><tr></tab><td bo-text="watcherCount"></td></tr></table-->
    <span>{{watcherCount}}</span>
    
  </body>

</html>

Try pressing "Get Watchers" and see that the watcher count is initially 3. Then write something or copy/paste into the first input and press "Get Watchers" again. Voila the watcher count decreased to 2 because the one time binding on the second input got evaluated when it got a value and it then removed its watcher.

Upvotes: 0

Related Questions