简体   繁体   中英

angularjs $window.onclick performs better than ng-click

I had a scenario where I have to make some alterations in localstorage as well as in some other data of the controller, this logic was supposed to be done on click of anywhere in whole page. This code was supposed to close all colorpickers if click was done anywhere on the body but not on the colorpicker button, but if clicked on colorpicker button then close all others colorpickers and open only the respective one. First I tried using ng-click which was working okay but the pace of closing all colorpickers and opening of respective one was very slow.

Note that I tried using $scope.$apply(); but that didn't work but instead it started giving me error that angularjs digestion is already in progress. Then I used $window.onclick which worked perfectly and the pace of colorpickers closing and opening was also very fine. I am wondering why $window.onclick worked better than ng-click . That function is as follows

$window.onclick = function (e) {
        var labels = getAllLabels(vm.allData);
        if (!e.target.classList.contains('color-picker-button') || e.target.classList.contains('color-picker-popup') || e.target.classList.contains('buttons-popup-charts')) {
            for (var i = 0; i < labels.length; i++) {
                labels[i].isOpen = false;
                localStorageService.set(labels[i].name + '-isOpen-alpha', false);
            }
            init();
        }
        if (e.target.classList.contains('legends-charts')) {
            var id = e.target.id;
            for (var i = 0; i < labels.length; i++) {
                if (labels[i].name === id) {
                    labels[i].isOpen = !labels[i].isOpen;
                } else {
                    labels[i].isOpen = false;
                }
                localStorageService.set(labels[i].name + '-isOpen-alpha', labels[i].isOpen);
            }
            init();
        }
    };

$window is a reference to the browser's window object. (See here for details: https://docs.angularjs.org/api/ng/service/$window )

ng-click causes a digest cycle through $scope.$apply . (Details here: https://docs.angularjs.org/guide/scope )

Relevant part:

Listener directives, such as ng-click, register a listener with the DOM. When the DOM listener fires, the directive executes the associated expression and updates the view using the $apply() method.

Therefore, $window.onclick executes faster, because it doesn't cause a digest cycle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM