26

我的代码中有这样的地方:

<input data-ng-disabled="SOME_SCOPE_VARIABLE" />

我也希望能够像这样使用它:

<input data-ng-autofocus="SOME_SCOPE_VARIABLE" />

或者更好的是,模仿 ng-style 的完成方式:

<input data-ng-attribute="{autofocus: SOME_SCOPE_VARIABLE}" />

这在当前版本的 AngularJS 中是否存在?我注意到在代码中有一个 BOOLEAN_ATTR 可以获取 AngularJS 支持的所有属性。我不想修改它,因为害怕更改版本并忘记更新。

4

10 回答 10

43

更新:AngularJS 现在有一个指令来评估焦点ngFocus的表达式,但为了完整起见,我在这里提到它。


当前版本的 AngularJS 没有焦点指令,但它在路线图中。巧合的是,我们昨天在邮件列表上讨论了这个,我想出了这个:

angular.module('ng').directive('ngFocus', function($timeout) {
    return {
        link: function ( scope, element, attrs ) {
            scope.$watch( attrs.ngFocus, function ( val ) {
                if ( angular.isDefined( val ) && val ) {
                    $timeout( function () { element[0].focus(); } );
                }
            }, true);

            element.bind('blur', function () {
                if ( angular.isDefined( attrs.ngFocusLost ) ) {
                    scope.$apply( attrs.ngFocusLost );

                }
            });
        }
    };
});

根据您的要求,它适用于范围变量:

<input type="text" ng-focus="isFocused" ng-focus-lost="loseFocus()">

这是一个小提琴:http: //jsfiddle.net/ANfJZ/39/

于 2013-02-13T17:41:36.350 回答
15

您可以使用内置的ngAttr 属性绑定来做到这一点。

<input ng-attr-autofocus="{{SOME_SCOPE_VARIABLE}}">

如果定义了 autofocus 属性SOME_SCOPE_VARIABLE(即使它是false),则会添加,如果是undefined. 所以我强迫虚假值是undefined.

$scope.SOME_SCOPE_VARIABLE = someVar || undefined;
于 2015-09-01T23:32:26.537 回答
5

该指令应该可以解决问题:

angular.module('utils.autofocus', [])
.directive('autofocus', ['$timeout', function($timeout) {
  return {
    restrict: 'A',
    scope: {'autofocus':'='}
    link : function($scope, $element) {
      $scope.$watch 'autofocus', function(focus){
        if(focus){
          $timeout(function() {
            $element[0].focus();
          });
        }
      }
    }
  }
}]);

取自这里:https ://gist.github.com/mlynch/dd407b93ed288d499778

于 2015-07-23T09:58:47.083 回答
1
scope.doFocus = function () {
                $timeout(function () {
                        document.getElementById('you_input_id').focus();
                    });
            };
于 2016-09-05T12:58:13.470 回答
1

创建这样的指令

.directive('autoFocus', ['$timeout', function ($timeout) {
        return {
            restrict: 'A',
            link: function ($scope, $element) {
                $timeout(function () {
                    $element[0].focus();
                });
            }
        }



<input type="text" auto-focus class="form-control msd-elastic" placeholder="">
于 2017-09-29T02:33:30.617 回答
0

我用两个自定义指令做到了,如下所示:

(function(angular) {
  'use strict';

  /* @ngInject */
  function myAutoFocus($timeout) {
    return {
      restrict: 'A',
      link: function(scope, element) {
        $timeout(function() {
          element[0].focus();
        }, 300);
      }
    };
  }

  function myFocusable() {
    return {
      restrict: 'A',
      link: function(scope, element, attrs) {
        var focusMethodName = attrs.myFocusable;
        scope[focusMethodName] = function() {
          element[0].focus();
        };
      }
    };
  }

  angular
    .module('myFocusUtils', [])
    .directive('myAutoFocus', myAutoFocus)
    .directive('myFocusable', myFocusable);

}(angular));

如果my-auto-focus为元素添加属性,它将在 300 毫秒后获得焦点。我将值设置为 300 而不是 0,以便在设置焦点之前加载其他异步组件。

该属性my-focusable将在当前范围内创建一个函数。此函数将在调用时将焦点设置到元素。当它在范围内创建某些内容时,请小心避免覆盖某些内容。

这样你就不需要在 Angular 的摘要循环 ( watch) 中添加一些东西,并且可以完全在视图中完成:

<input my-focusable="focusOnInput"></input>        
<button ng-click="focusOnInput()">Click to focus</button>

我创建了一个 JSFiddle 来显示myFocusable指令:http: //jsfiddle.net/8shLj3jc/

出于某种我不知道的原因,该myAutoFocus指令在 JSFiddle 中不起作用,但它在我的页面中起作用。

于 2014-11-12T13:16:11.723 回答
0

我所做的是对我的输入使用常规自动对焦:<input autofocus>

然后当角度准备好时,我将焦点设置在第一个可见输入上,并使用自动对焦:

angular.element(document).ready(function() {
  $('input[autofocus]:visible:first').focus();
});

希望这可以帮助。

于 2013-11-13T17:23:06.230 回答
0
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="namesCtrl"> 
  <div ng-repeat="x in names">
     <input ng-attr-focus={{$first}} value="{{x.name + ', ' + x.country }}" />
  </div>
</div>

<script>

        var myApp = angular.module('myApp', []);
        myApp.controller('namesCtrl', function($scope) {
    $scope.names = [
        {name:'x1',country:'y1'},
        {name:'x2',country:'y2'},
        {name:'x3',country:'y3'}
    ];
});

        myApp.directive("focus", function(){
            return {
                restrict: "A",
                link: function link(scope, element, attrs) {

                      if(JSON.parse(attrs.focus)){
                          element[0].focus();
                      }
                }
            };
        });
</script>
</body>
</html>

为我的一个用例创建了上面的自定义指令。

  • 始终专注于第一个输入元素。
  • 适用于 ajax 数据、浏览器后退/前进按钮。
  • 在 chrome 和 firefox 上测试(这里不支持默认自动对焦)

JSON.parse 用于将 html 返回的字符串“true”解析为 JS 中的 boolean true。
另一种将 attrs.focus === "true" 用于 if 条件的方法。

于 2017-07-30T17:38:01.097 回答
0

结合上面提到的其他人:

JS代码:

myApp.directive('ngAutofocus', ['$timeout', function ($timeout) {
    var linker = function ($scope, element, attrs) {
        $scope.$watch('pageLoaded', function (pageLoaded) {
            if (pageLoaded) {
                $timeout(function () {
                    element[0].focus();
                });
            }
        });
    };

    return {
        restrict: 'A',
        link: linker
    };
}]);

HTML:

  <input type="text" ng-model="myField" class="input-block-level edit-item" ng-autofocus>

从页面获取的初始加载方法将 pageLoaded 设置为 true:

    var loadData = function () {
        ..
        return $http.get(url).then(function (requestResponse) {
           $scope.pageLoaded = true;
......
}
于 2020-08-04T13:40:36.787 回答
0

所以没有 $timeout 你也可以像这样使用自动对焦 -

    <input type="text" ng-show="{{condition}}" class='input-class'></input>
    angular.element(document).ready(function(){
    angular.element('.input-class')[0].focus();
    });
于 2018-06-06T06:32:43.547 回答