angular directive encapsulating a delay for ng-change

前端 未结 4 717
南笙
南笙 2020-11-28 09:21

I have a search input field with a requery function bound to the ng-change.

 
4条回答
  •  感动是毒
    2020-11-28 10:04

    This works perfectly for me: JSFiddle

      var app = angular.module('app', []);
        app.directive('delaySearch', function ($timeout) {
            return {
                restrict: 'EA',
                template: ' ',
                link: function ($scope, element, attrs) {
                    $scope.modelChanged = function () {
                        $timeout(function () {
                            if ($scope.lastSearch != $scope.search) {
                                if ($scope.delayedMethod) {
                                    $scope.lastSearch = $scope.search;
                                    $scope.delayedMethod({ search: $scope.search });
                                }
                            }
                        }, 300);
                    }
                },
                scope: {
                    delayedMethod:'&'
                }
            }
        });
    

    Using the directive

    In your controller:

    app.controller('ctrl', function ($scope,$timeout) {
        $scope.requery = function (search) {
            console.log(search);
        }
    });
    

    In your view:

提交回复
热议问题