我正在尝试使用自定义指令从一开始就选择并聚焦文本输入字段。
输入字段:
<input type="text" value="Preset Value" select-on-load />
自定义指令:
app.directive('selectOnLoad', function () {
// Linker function
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.focus().select();
}
};
});
但我只收到一个 javscript 错误,指出 focus/select 不是一个函数。 我还应该怎么做?
最佳答案
Angular 的 jqLite(内置轻量级 jQuery 版本)不支持 .focus()
。
您需要获取实际的 DOM 元素并使用 Javascript 的内置 .focus()
element[0].focus()
(element[0]
从 jqLite 包装器 element
获取 DOM 元素对象)
使用 .select()
时,如果您尝试选择通过 ng-model
提供的文本,会有点棘手,因为到了 link
函数运行时,ng-model
的值尚未被插值并插入到 DOM 中。
您需要等到摘要周期结束,我见过的常见方法是通过$timeout
:
$timeout(function(){
element[0].select();
});
关于javascript - Angularjs:选择并聚焦指令链接中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28195438/