【发布时间】:2013-09-28 06:54:05
【问题描述】:
我正在使用以下指令来监听输入元素上的输入按键:
.directive('ngEnter', function () {
return function (scope, element, attrs) {
element.bind("keypress", function (event) {
if(event.which === 13) {
scope.$apply(function (){
scope.$eval(attrs.ngEnter);
});
event.preventDefault();
}
});
};
})
这按预期工作。当我在输入元素上添加工具提示指令时,上述指令不再起作用。有解决方法吗?
更新
在 bingjie2680 的建议下,我尝试使用 ng-keypress 和 ng-keydown,但偶然发现了另一个问题。上述指令似乎会影响同一元素的 ng-model 指令。模型变得未定义。这是输入标签:
<input type="text" placeholder="tags"
tooltip="tooltip text here"
tooltip-placeent="top"
tooltip-trigger="focus"
ng-model="currentTag" ng-keydown="addTag($event)" />
这里是 addTag 的相关部分:
$scope.addTag = function($event) {
if ($event.keyCode !== 13) return;
console.log($scope.currentTag); <-- currentTag is undefined here
...
}
为什么模型变得未定义?如果我不包含工具提示指令,一切正常。
【问题讨论】:
-
为什么需要工具提示指令? Bootstrap 有
tooltip属性 -
好吧,我没有,但我依赖 ui.bootstrap 来执行其他指令,并且 ui.bootstrap 与 bootstrap 2.3.2 兼容。我只能在最新(3.0.0)版本中找到工具提示组件。
-
angular 有 ng-keypress 指令,你可以使用它并将你的逻辑放在控制器中。
-
@bingjie2680 谢谢,我会试试的。
-
查看更新后的帖子。 ng-keypress 有效,但必须将模板中的 addTag 更改为 addTag($event, currentTag) 以将 currentTag 的值保存在函数的范围内。这是正常的还是我错过了什么? currentTag 不应该也可以作为 $scope.currentTag 从控制器访问吗?
标签: angularjs angularjs-directive angular-ui angular-ui-bootstrap