4

I've got a site where i need to get some debounce functionality on a click event, and i've searched the web to find a proper solution but hasn't been able.

i got two link, each link get its own type of data, and this data is used in a list underneath.

<li ng-class="{'active' : type == 'own'}">
    <a ng-click="changeType('own')" href="#"><span aria-hidden="true" class="icon icon-user"></span> Mine arbejdsgrupper</a>
</li>
<li ng-class="{'active' : type == 'all'}">
    <a ng-click="changeType('all')" href="#"><span aria-hidden="true" class="icon icon-cabinet"></span> Foreslåede arbejsgrupper</a>
</li>

If i switch fast, (click the first, then the second) the async fetch to get the data can't follow, so something i get content from the first link in the list even if i click the second first.

i can see that there is a ng-model-options, but i can't figure out if i can it here. And i would be sad if i needed to use underscore debounce, so i need to $scope.$apply every change to the scope.

Anyone got some ideers for this ?

EDIT!

A friend send me this. How to write a debounce service in AngularJS It should solve the problem.

Community
  • 1
  • 1
Ngschumacher
  • 140
  • 1
  • 10
  • Possible duplicate of [How to write a debounce service in AngularJS](http://stackoverflow.com/questions/13320015/how-to-write-a-debounce-service-in-angularjs) – Wallace Vizerra Aug 19 '16 at 16:24

1 Answers1

2

You are thinking about this at the wrong level. As a rule of thumb I think the UI should only have really simple interactions mainly just function calls i.e. I try and limit the expressions and logic in the UI.

So I would debounce in the controller after those methods have been clicked.

angular.module('app-controlllers').controller('ACtrl', [
'$scope',
function ($scope) {
    var debounceAllFn = _.debouce(function () {
        // your actual function implementation
    }. 500),
    debounceOwnFn = _.debouce(function () {
        // your actual function implementation
    }. 500);

    $scope.changeType = function (type) {
        switch (type.toLowerCase()) {
            'all' : 
                debounceAllFn();
                break;
            'own' : 
                debounceOwnFn();
                break;
        }
    }
}
]);
Jon
  • 4,295
  • 6
  • 47
  • 56