【问题标题】:Why does my input focus directive no longer work?为什么我的输入焦点指令不再起作用?
【发布时间】:2015-06-29 21:12:51
【问题描述】:

http://plnkr.co/edit/fXo21LnphHZ3qWnuEMFt?p=preview

我有一个指令,假设一旦光标可见,它就会自动将光标聚焦到输入中。

此方法可以使用,但升级到 Angular 1.4.1 后不再使用

标记

<div class="sidebar" ng-controller="sidebar">

  <div class="btn-search"
       ng-hide="showingTagSearchInput"
       ng-click="quickSearchTags()">Search</div>

  <div class="search-tags-input container-fluid" ng-show="showingTagSearchInput">
      <input type="text"
             focus-me="showingTagSearchInput"
             placeholder="search for a tag"
             ng-model="tagSearchInput"
             class="form-control">
  </div>
</div>

侧边栏控制器

function quickSearchTags() {
    vs.showingTagSearchInput = !vs.showingTagSearchInput;
}

我的 focusMe 指令

.directive('focusMe', ['$timeout', '$parse', function($timeout, $parse) {
    return {
        link: function(scope, element, attrs) {
            var model = $parse(attrs.focusMe);
            scope.$watch(model, function(value) {
                console.log('value ', value);
                console.log('element ', element);
                if (value === true) { 
                    $timeout(function() {
                        // element[0].focus(); 
                        element[0].onfocus = true; 
                    });
                }
            });
            element.bind('blur', function() {
                scope.$apply(model.assign(scope, false));
            })
        }
    }
}])

【问题讨论】:

    标签: javascript angularjs events input angularjs-directive


    【解决方案1】:

    您应该使用element[0].focus(); 而不是element[0].onfocus = true;

    element[0].focus() 将专注于指令模板的第一个元素。

    代码

    $timeout(function() {
        element[0].focus(); 
    });
    

    Demo Plunkr

    【讨论】:

    • 啊酷,是的,确实有效......但它在我的实际 Angular 应用程序中不起作用:( 嗯,标记这个,可能会提出另一个问题。谢谢!
    • @LeonGaban 它应该以任何方式工作..您是否在您的应用程序和 plunkr 中尝试过此代码
    • 是的,它适用于 plunkr,但由于某种原因不适用于我的应用程序 :( 它也使用...但我有一个更重要的不同问题,将在几秒钟内发布一个新问题
    • 你介意看看这个吗? stackoverflow.com/questions/31125880/…
    • @LeonGaban 当然..会做..谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 2020-12-21
    • 2016-10-03
    • 1970-01-01
    • 2014-08-13
    • 1970-01-01
    相关资源
    最近更新 更多