Angularjs: why there are 3 watchers for 1 binding?
Asked Answered
S

1

8

Please take a look at the screenshot given below

enter image description here

As you can see in the screenshot above there are #3 watchers for a single binding.

Can anyone please elaborate why is it so?

P.S: I am using AngularJS Batarang for checking the performance.

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

app.controller('appCtrl', function ($scope, $timeout) {
    $scope.name = 'vikas bansal';
})
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
    <script src="app.js"></script>
</head>

<body>
    <div ng-app="app" ng-controller="appCtrl">
        {{name}}
    </div>
</body>

</html>
Sandstorm answered 12/10, 2016 at 6:57 Comment(0)
P
1

I think Angular Batarang has a wrong counter of watchers. I checked with few different sources, and all except AngularJS Batarang show me single watcher on your code. Check out this question with function:

(function () { 
    var root = angular.element(document.getElementsByTagName('body'));

    var watchers = [];

    var f = function (element) {
        angular.forEach(['$scope', '$isolateScope'], function (scopeProperty) { 
            if (element.data() && element.data().hasOwnProperty(scopeProperty)) {
                angular.forEach(element.data()[scopeProperty].$$watchers, function (watcher) {
                    watchers.push(watcher);
                });
            }
        });

        angular.forEach(element.children(), function (childElement) {
            f(angular.element(childElement));
        });
    };

    f(root);

    // Remove duplicate watchers
    var watchersWithoutDuplicates = [];
    angular.forEach(watchers, function(item) {
        if(watchersWithoutDuplicates.indexOf(item) < 0) {
             watchersWithoutDuplicates.push(item);
        }
    });

    console.log(watchersWithoutDuplicates.length);
})();

And you can check Watchers extension for chrome. Both show 1 watcher.

Polyhymnia answered 20/10, 2016 at 9:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.