我怎样才能让angularjs ngChange处理程序只有当用户input完成时才被调用

我有一个input字段,我想要应用ngChange的变体。

input字段是与ajax调用的绑定,当用户改变input时,服务器端将处理数据,但是,我不想太频繁地调用这个调用。

假设用户想要input一个真正的string,我只想在用户完成他即将input的单词之后才能进行呼叫。 不过,我不想使用模糊等事件。 什么是更好的方式来实现这个,而不是setTimeout

在Angular> 1.3中使用ng-model-options

  <input type="text" ng-model="vm.searchTerm" ng-change="vm.search(vm.searchTerm)" ng-model-options="{debounce: 750}" /> 

没有ng-model-options – 在标记中:

 <input ng-change="inputChanged()"> 

在你的支持控制器/范围

 var inputChangedPromise; $scope.inputChanged = function(){ if(inputChangedPromise){ $timeout.cancel(inputChangedPromise); } inputChangedPromise = $timeout(taskToDo,1000); } 

那么你的taskToDo将只运行1000毫秒后没有变化。

从Angular 1.3开始,你可以使用Angular ng-model-options指令

 <input ng-change="inputChanged()" ng-model-options="{debounce:1000}"> 

资料来源: https : //stackoverflow.com/a/26356084/1397994

编写你自己的指令 – 这只会根据你设置的条件在myText上运行命令

 <input my-change-directive type="text ng-model="myText" /> .directive('myChangeDirective',function() { return { require : 'ngModel', link : function($scope,$element,$attrs) { var stringTest = function(_string) { //test string here, return true //if you want to process it } $element.bind('change',function(e) { if(stringTest($attrs.ngModel) === true) { //make ajax call here //run $scope.$apply() in ajax callback if scope is changed } }); } } })