我正在尝试重新创建与 myspace.com 相同的功能。基本上,他们拥有的是一个搜索模式,只要您开始在页面上的任何位置(任何按键)输入内容,该模式就会自动出现。
我在这个 plnkr http://plnkr.co/edit/Cw6isK?p=preview 中有代码
我无法让它正常工作。本质上,我想做的是制定一个指令来监听 $document 上的按键事件。然后,一旦按下按键,就会打开带有搜索框的快速搜索模式,以便用户可以继续输入他/她的搜索查询。
问题是我无法让它工作。我无法找到将按键绑定(bind)/链接到指令搜索输入框的方法。
app.directive('quickSearch', function($timeout, $document) {
return {
restrict: 'AE',
templateUrl: 'quickSearch.html',
scope: {
selected: '=',
isOpen: '@'
},
link: function(scope, elem, attrs) {
var arr = [];
$document.bind('keyup', function(e) {
scope.selected.isOpen = true;
//here i'm trying to link/bind the keypresses to the scope, but not sure if this is a good way of doing it
scope.selected.query += e.key
});
scope.$watch('scope.selected.isOpen', function() {
if(scope.selected.isOpen){
$timeout(function() {
elem.find('input')[0].focus()
}, 1)
}
})
}
}
})
最佳答案
你已经快到了,你只是忘记了手动绑定(bind)的 DOM 事件(不是使用 ng* 指令)不会自动触发新的摘要周期。所以你只需要手动启动摘要。另外,您可能需要类似 String.fromCharCode(e.keyCode);
而不是 e.key
并在 peypress
事件上执行此操作:
$document.bind('keypress', function(e) {
scope.selected.isOpen = true;
scope.selected.query += String.fromCharCode(e.keyCode);
scope.$apply();
});
关于javascript - 创建出现在按键上的 Angular 模态指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33723077/