【问题标题】:catch ng-show event and focus input field捕捉 ng-show 事件并聚焦输入字段
【发布时间】:2014-05-11 16:23:04
【问题描述】:

我不想写复杂的指令只是为了集中注意力。如果该方法将使用纯 js,它是可以接受的。我的问题是如何捕捉 Angular 的 ng-show。

<a ng-click="showInput=true">show</a>
<input type="text" ng-show="showInput" />

上面的代码显示了输入,如何关注它的外观?

【问题讨论】:

  • 不确定您的项目是否需要它,但请记住,您不能以编程方式将focus 触发到 iOS 设备上的元素中(必须通过单击/点击完成),但是您可以遍历设置第一个焦点后的元素stackoverflow.com/questions/18728166/…

标签: javascript jquery angularjs


【解决方案1】:

你可以添加这个指令:

app.directive('showFocus', function($timeout) {
  return function(scope, element, attrs) {
    scope.$watch(attrs.showFocus, 
      function (newValue) { 
        $timeout(function() {
            newValue && element.focus();
        });
      },true);
  };    
});

并像这样使用它:

<input type="text" ng-show="showInput" show-focus="showInput">

【讨论】:

    【解决方案2】:

    您可以尝试使用像这样的简单指令:

    app.directive('FocusOnVisibility', function () {
        return function (scope, element, attrs) {
            //Watch the showInput model
            scope.$watch('showInput', function () {
                //If the model changes to true, focus on the element
                if (scope.showInput === true) {
                    //Assumes that the element has the focus method
                    //If not, then you can have your own logic to focus here
                    element.focus();
                }
            });
        };
    });
    

    然后你可以在你的标签中使用这个指令:

    <input type="text" ng-show="showInput" focus-on-visibility>
    

    【讨论】:

    • 不起作用,这是有道理的,但就是不起作用。未发现错误。
    • 如果不起作用,则不应将其标记为答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-31
    • 1970-01-01
    • 1970-01-01
    • 2022-09-29
    • 2014-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多