Can I debounce or throttle a watched <input> in AngularJS using _lodash?

前端 未结 4 1178
长发绾君心
长发绾君心 2020-12-08 03:54

I have the following which does a watch on an field that\'s bound to $scope.id. Every time the input field value changes the watch function gets e

4条回答
  •  一个人的身影
    2020-12-08 04:42

    Is that what are you looking for?

    $scope.$watch("id", _.debounce(function (id) {
        // Code that does something based on $scope.id
        // This code will be invoked after 1 second from the last time 'id' has changed.
    }, 1000));
    

    Note, however, that if you want to change $scope inside that function you should wrap it $scope.$apply(...) as unless _.debounce function uses $timeout internally (which as far as I understand it doesn't do) Angular will not be aware of the changes you did on the $scope.

    UPDATE

    As to the updated question - yes you need to wrap the entire callback function body with

    $scope.$apply():

    $scope.$watch("id", _.debounce(function (id) {
        // This code will be invoked after 1 second from the last time 'id' has changed.
        $scope.$apply(function(){
            // Code that does something based on $scope.id
        })
    }, 1000));
    

提交回复
热议问题