在AngularJS中,“Angular的方法”是什么?

更具体的要求:

当打开一个模态时,将焦点设置在这个模态内预定义的<input>上。 每次<input>变得可见时(例如,通过单击某个按钮),将焦点设置在它上。

我尝试用自动对焦来实现第一个要求,但这只在Modal第一次打开时有效,并且只在某些浏览器中有效(例如在Firefox中它不起作用)。


当前回答

我发现使用一般的表达方式很有用。这样你就可以在输入文本有效时自动移动焦点

<button type="button" moo-focus-expression="form.phone.$valid">

或者当用户完成一个固定长度的字段时自动聚焦

<button type="submit" moo-focus-expression="smsconfirm.length == 6">

当然还有加载后的重点

<input type="text" moo-focus-expression="true">

该指令的代码:

.directive('mooFocusExpression', function ($timeout) {
    return {
        restrict: 'A',
        link: {
            post: function postLink(scope, element, attrs) {
                scope.$watch(attrs.mooFocusExpression, function (value) {

                    if (attrs.mooFocusExpression) {
                        if (scope.$eval(attrs.mooFocusExpression)) {
                            $timeout(function () {
                                element[0].focus();
                            }, 100); //need some delay to work with ng-disabled
                        }
                    }
                });
            }
        }
    };
});

其他回答

如果你想把焦点设置在特定的元素上,你可以使用下面的方法。

创建一个名为focus的服务。 angular.module(“应用程序”) .factory('focus', function ($timeout, $window) { 返回函数(id) $timeout(函数){ var element = $window.document.getElementById(id) 如果(元素) element.focus (); }); }; }); 将它注入到您希望调用的控制器中。 调用此服务。

你可以使用下面的指令,在HTML输入中获取一个bool值来关注它…

//js file
angular.module("appName").directive("ngFocus", function () {
       return function (scope, elem, attrs, ctrl) {
             if (attrs.ngFocus === "true") {
                 $(elem).focus();
             }
             if (!ctrl) {
                 return;
             }
       elem.on("focus", function () {
            elem.addClass("has-focus");
            scope.$apply(function () {
                ctrl.hasFocus = true;
            });
        });
    };
});

<!-- html file -->
<input type="text" ng-focus="boolValue" />

你甚至可以在控制器中设置一个函数为ngFocus指令值 注意下面的代码…

<!-- html file -->
<input type="text" ng-focus="myFunc()" />


//controller file
$scope.myFunc=function(){
      if(condition){
          return true;
      }else{
          return false;
      }
}

这个指令发生在HTML页面渲染时。

HTML有一个属性autofocus。

<input type="text" name="fname" autofocus>

http://www.w3schools.com/tags/att_input_autofocus.asp

我写了一个双向绑定焦点指令,就像最近的model。

你可以像这样使用focus指令:

<input focus="someFocusVariable">

如果你在控制器的任何地方设置someFocusVariable范围变量为真,输入就会被聚焦。如果你想“模糊”你的输入,someFocusVariable可以设置为false。这就像Mark Rajcok的第一个答案,但是有双向绑定。

下面是指令:

function Ctrl($scope) {
  $scope.model = "ahaha"
  $scope.someFocusVariable = true; // If you want to focus initially, set this to true. Else you don't need to define this at all.
}

angular.module('experiement', [])
  .directive('focus', function($timeout, $parse) {
    return {
      restrict: 'A',
      link: function(scope, element, attrs) {
          scope.$watch(attrs.focus, function(newValue, oldValue) {
              if (newValue) { element[0].focus(); }
          });
          element.bind("blur", function(e) {
              $timeout(function() {
                  scope.$apply(attrs.focus + "=false"); 
              }, 0);
          });
          element.bind("focus", function(e) {
              $timeout(function() {
                  scope.$apply(attrs.focus + "=true");
              }, 0);
          })
      }
    }
  });

用法:

<div ng-app="experiement">
  <div ng-controller="Ctrl">
    An Input: <input ng-model="model" focus="someFocusVariable">
    <hr>
        <div ng-click="someFocusVariable=true">Focus!</div>  
        <pre>someFocusVariable: {{ someFocusVariable }}</pre>
        <pre>content: {{ model }}</pre>
  </div>
</div>

这是小提琴:

http://fiddle.jshell.net/ubenzer/9FSL4/8/

以编程方式调用元素上的任何操作:click(), focus(), select()…

用法:

<a href="google.com" auto-action="{'click': $scope.autoclick, 'focus': $scope.autofocus}">Link</a>

指令:

/**
 * Programatically Triggers given function on the element
 * Syntax: the same as for ng-class="object"
 * Example: <a href="google.com" auto-action="{'click': autoclick_boolean, 'focus': autofocus_boolean}">Link</a>
 */
app.directive('focusMe', function ($timeout) {
    return {
        restrict: 'A',
        scope: {
            autoAction: '<',
        },
        link: function (scope, element, attr) {
            const _el = element[0];
            for (const func in scope.autoAction) {
                if (!scope.autoAction.hasOwnProperty(func)) {
                    continue;
                }
                scope.$watch(`autoAction['${func}']`, (newVal, oldVal) => {
                    if (newVal !== oldVal) {
                        $timeout(() => {
                            _el[func]();
                        });
                    }
                });
            }

        }
    }
});

要解决这个问题,最好在controller或ng-init中设置初始化变量:

 <input ng-init="autofocus=true" auto-action="{'focus': autofocus}">