【问题标题】:Angular directive on div, element has no focus methoddiv上的角度指令,元素没有焦点方法
【发布时间】:2013-10-28 10:40:33
【问题描述】:

我有一个角度指令,我将其放入 div 元素中。在我的一个链接中:我调用element.focus() 的函数。我收到控制台错误:Object [object Object] has no method focus

我调用 alert(element 前一行,它说元素是[[object HTMLDivElement]]

在调用焦点之前我需要以某种方式将元素转换为 div 吗?

这是一个指令,

tsUui.directive('userList', function(){
    return{
        restrict: 'A',
                link: function (scope, elem, attrs){
                    scope.something=function() {
                       elem.focus();
                    };
                }
        });

这是该项目的大部分内容:http://plnkr.co/edit/SiBDuylEv1LUCuWCv5Ep?p=preview

重现错误:单击其中一个用户行,您将收到警报(elem)。如果您查看控制台,您会看到焦点错误。

【问题讨论】:

  • 你能在 Fiddle 中发布你的代码吗?
  • 添加了一些代码,和描述的差不多。正如我所说,它知道它是一个 HTMLdivElement
  • 你的项目中有 jQuery 还是只有 angular.js 中的 jqLit​​e?
  • 伙计,我真的很抱歉,但没有看到您的问题在 Plunker/Fiddle 中重现,我们只能使用“假设/可能/”之类的词。请节省您和我们的时间:)。你在哪里使用指令,你使用的巫婆elelnt......谢谢
  • 你的意思是$(elem).focus()

标签: javascript angularjs angularjs-directive


【解决方案1】:

在渲染元素之前调用链接函数,因此 focus() 通常不起作用。这是一个示例,其中指令上的“链接”属性分为“前”和“后”,用于前链接和后链接功能。

Working Example: http://plnkr.co/edit/Fj59GB

// this is the directive you add to any element you want to highlight after creation
Guest.directive('autoFocus', function() {
    return {
        link: {
            pre: function preLink(scope, element, attr) {
                console.debug('prelink called');
                // this fails since the element hasn't rendered
                //element[0].focus();
            },
            post: function postLink(scope, element, attr) {
                console.debug('postlink called');
                // this succeeds since the element has been rendered
                element[0].focus();
            }
        }
    }
});
<input value="hello" />
<!-- this input automatically gets focus on creation -->
<input value="world" auto-focus />

Full AngularJS Directive Docs: https://docs.angularjs.org/api/ng/service/$compile

【讨论】:

    【解决方案2】:

    如果您在 AngularJS 之前加载 jQuery,Angular 将使用 jQuery 代替 jqLit​​e(包含在 AngularJS 中)。然后你可以使用elem.focus(); 否则,正如 stevuu 所说,您必须使用$(elem).focus();

    【讨论】:

      猜你喜欢
      • 2015-06-12
      • 2014-10-25
      • 2015-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 2023-03-09
      • 2016-12-27
      相关资源
      最近更新 更多