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

前端之家收集整理的这篇文章主要介绍了angularjs – 以角度方式设置元素焦点前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在查找了如何设置焦点元素与角度的例子后,我看到他们大多使用一些变量来观察,然后设置焦点,他们大多数使用一个不同的变量,他们想要设置焦点的每个字段。在一种形式,有很多字段,意味着在很多不同的变量。

用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>
原文链接:https://www.f2er.com/angularjs/146914.html

猜你在找的Angularjs相关文章