Implement a delay on $scope.$watch

前端 未结 5 1665
醉话见心
醉话见心 2021-02-07 03:33

I was wondering whether or not it is possible to implement a slight delay on $scope.$watch. I have the following which queries the server, so I\'d like to implement a slight del

5条回答
  •  不要未来只要你来
    2021-02-07 03:56

    I like to use Lo-Dash which provides two really useful capabilities: debounce and throttle which does exactly what you want. Let's say you want to make sure it only calls the function once per 150 ms:

    function update() {
     $scope.loading = true;
        returnFactory.query($scope.query).then(function (returns) {
            $scope.returns = returns;
            $scope.loading = false;
        });
    }
    
    $scope.$watch("query", function () {
       _.throttle(update, 150);
    });
    

    The throttle function lets you control when the update function is called (trailing or leading edge).

    I use Lo-Dash all the time in my app. It is a must-have library for me... more useful than jQuery. But, you can create a custom build of Lo-Dash which only includes the throttle and debounce functions if you don't want to include the entire library.

提交回复
热议问题