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

更具体的要求:

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

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


当前回答

你可以使用下面的指令,在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页面渲染时。

其他回答

我想在寻找一个更好的解决方案,但没有找到它,而是不得不创造它之后,为这个讨论做出贡献。

标准: 1. 解决方案应该独立于父控制器范围,以增加可重用性。 2. 避免使用$watch来监视某些条件,这既缓慢,又增加了摘要循环的大小,并且使测试更加困难。 3.避免$timeout或$scope.$apply()触发摘要循环。 4. input元素出现在使用Directive打开的元素中。

这是我最喜欢的解决方案:

指令:

.directive('focusInput', [ function () {
    return {
        scope: {},
        restrict: 'A',
        compile: function(elem, attr) {
            elem.bind('click', function() {
                elem.find('input').focus();                
            });
        }        
    };
}]);

Html:

 <div focus-input>
     <input/>
 </div>

我希望这篇文章能帮助到一些人!

我认为这个指令是不必要的。使用HTML id和类属性选择所需的元素,并让服务使用文档。getElementById或document。querySelector来应用焦点(或jQuery等价物)。

标记是标准的HTML/angular指令,添加了id/classes供选择

<input id="myInput" type="text" ng-model="myInputModel" />

控制器广播事件

$scope.$emit('ui:focus', '#myInput');

在UI服务中使用querySelector -如果有多个匹配项(比如由于类),它将只返回第一个

$rootScope.$on('ui:focus', function($event, selector){
  var elem = document.querySelector(selector);
  if (elem) {
    elem.focus();
  }
});

您可能希望使用$timeout()强制一个摘要循环

这可能是ES6时代最简单的解决方案。

添加下面的一行指令使得HTML的“autofocus”属性在Angular.js上有效。

.directive('autofocus', ($timeout) => ({link: (_, e) => $timeout(() => e[0].focus())}))

现在,你可以使用HTML5自动对焦语法,比如:

<input type="text" autofocus>

如果你正在使用modalInstance并且拥有对象,你可以在打开模式后使用“then”来执行操作。如果你没有使用modalInstance,并硬编码打开模态,你可以使用事件。$timeout不是一个好的解决方案。

你可以做(Bootstrap3):

$("#" + modalId).on("shown.bs.modal", function() {
    angular.element("[name='name']").focus();
});

在modalInstance中,您可以查看如何在打开modal后执行代码的库。

不要像这样使用$timeout, $timeout可以是0、1、10、30、50、200或更多,这将取决于客户端计算机,以及打开模式的进程。

不要使用$timeout,让方法告诉你什么时候可以聚焦;)

希望这对大家有所帮助!:)

以编程方式调用元素上的任何操作: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}">