加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 以角度方式设置元素焦点

发布时间:2020-12-17 09:09:12 所属栏目:安全 来源:网络整理
导读:在查找了如何设置焦点元素与角度的例子后,我看到他们大多使用一些变量来观察,然后设置焦点,他们大多数使用一个不同的变量,他们想要设置焦点的每个字段。在一种形式,有很多字段,意味着在很多不同的变量。 用jquery的方式,但想要以角度的方式做,我做了
在查找了如何设置焦点元素与角度的例子后,我看到他们大多使用一些变量来观察,然后设置焦点,他们大多数使用一个不同的变量,他们想要设置焦点的每个字段。在一种形式,有很多字段,意味着在很多不同的变量。

用jquery的方式,但想要以角度的方式做,我做了一个解决方案,我们设置焦点在任何函数使用元素的id,所以,因为我是非常新的角度,我想得到一些意见,如果那种方式是正确的,有问题,无论什么,任何可以帮助我做这个更好的方式在角。

基本上,我创建一个指令,监视用户使用指令定义的范围值,或默认的focusElement,当该值与元素的id相同时,该元素集本身的焦点。

angular.module('appnamehere')
  .directive('myFocus',function () {
    return {
      restrict: 'A',link: function postLink(scope,element,attrs) {
        if (attrs.myFocus == "") {
          attrs.myFocus = "focusElement";
        }
        scope.$watch(attrs.myFocus,function(value) {
          if(value == attrs.id) {
            element[0].focus();
          }
        });
        element.on("blur",function() {
          scope[attrs.myFocus] = "";
          scope.$apply();
        })        
      }
    };
  });

需要通过某种原因获得焦点的输入,将这样做

<input my-focus id="input1" type="text" />

这里设置焦点的任何元素:

<a href="" ng-click="clickButton()" >Set focus</a>

和设置焦点的示例函数:

$scope.clickButton = function() {
    $scope.focusElement = "input1";
}

这是一个好的解决方案在角?它有问题,我的糟糕的经验,我还没有看到?

您的解决方案的问题是,它绑定到其他指令创建一个新的范围,不能很好地工作。 ng重复。一个更好的解决方案是简单地创建一个服务函数,使您能够在控制器中强制地聚焦元素或在HTML中声明性地聚焦元素。

DEMO

JAVASCRIPT

服务

.factory('focus',function($timeout,$window) {
    return function(id) {
      // timeout makes sure that it is invoked after any other event has been triggered.
      // e.g. click events that need to run before the focus or
      // inputs elements that are in a disabled state but are enabled when those events
      // are triggered.
      $timeout(function() {
        var element = $window.document.getElementById(id);
        if(element)
          element.focus();
      });
    };
  });

指示

.directive('eventFocus',function(focus) {
    return function(scope,elem,attr) {
      elem.on(attr.eventFocus,function() {
        focus(attr.eventFocusId);
      });

      // Removes bound events in the element itself
      // when the scope is destroyed
      scope.$on('$destroy',function() {
        elem.off(attr.eventFocus);
      });
    };
  });

控制器

.controller('Ctrl',function($scope,focus) {
    $scope.doSomething = function() {
      // do something awesome
      focus('email');
    };
  });

HTML

<input type="email" id="email" class="form-control">
<button event-focus="click" event-focus-id="email">Declarative Focus</button>
<button ng-click="doSomething()">Imperative Focus</button>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读