http://jsbin.com/vozohexomo/4/edit?js,console,output
我有一个服务,可以进行$ http调用和两个指令。一个指令负责将数据传递给服务(my-input
),另一个指令负责处理服务的结果(my-output
)。
此处的目标是让用户能够进行实时搜索并实时显示结果。
现在它所做的只是为执行查询添加一个延迟,这是毫无意义的。如何在休息期之后才能执行查询?
app.service('httpFactory', function ($rootScope, $timeout) {
this.doQuery = function (query) {
$timeout(function(){
console.log("Executing: " + query);
$rootScope.data = "the result of query " + query;
}, 500);
};
});
app.directive('myInput', ['httpFactory', function(httpFactory) {
var link = function(scope, elem) {
scope.query = '';
scope.$watch('query', function() {
httpFactory.doQuery(scope.query);
});
};
return {
link: link,
restrict: 'E',
scope: {query: '='},
template: '<input ng-model="query">'
};
}]);
app.directive('myOutput', function($rootScope) {
var link = function(scope, elem) {
$rootScope.$watch('data', function(){
console.log("I see " + $rootScope.data);
});
};
return {
link: link,
restrict: 'E',
template: '<div>I see {{data}}</div>'
};
});
答案 0 :(得分:0)
http://jsbin.com/vozohexomo/5/edit?js,console,output
事实证明,解决方案比我认为的更简单。只需在tempQuery中保存每个查询,只执行$ timeout延迟后匹配的查询。
app.service('httpFactory', function ($rootScope, $timeout) {
var tempQuery;
this.doQuery = function (query) {
tempQuery = query;
$timeout(function(){
if (query == tempQuery) {
console.log("Executing: " + query);
$rootScope.data = "the result of query " + query;
}
}, 500);
};
});