在AngularJS中,“Angular的方法”是什么?
更具体的要求:
当打开一个模态时,将焦点设置在这个模态内预定义的<input>上。 每次<input>变得可见时(例如,通过单击某个按钮),将焦点设置在它上。
我尝试用自动对焦来实现第一个要求,但这只在Modal第一次打开时有效,并且只在某些浏览器中有效(例如在Firefox中它不起作用)。
在AngularJS中,“Angular的方法”是什么?
更具体的要求:
当打开一个模态时,将焦点设置在这个模态内预定义的<input>上。 每次<input>变得可见时(例如,通过单击某个按钮),将焦点设置在它上。
我尝试用自动对焦来实现第一个要求,但这只在Modal第一次打开时有效,并且只在某些浏览器中有效(例如在Firefox中它不起作用)。
当前回答
只是顺便送点咖啡。
app.directive 'ngAltFocus', ->
restrict: 'A'
scope: ngAltFocus: '='
link: (scope, el, attrs) ->
scope.$watch 'ngAltFocus', (nv) -> el[0].focus() if nv
其他回答
我发现其他一些答案过于复杂,而你真正需要的只是这个
app.directive('autoFocus', function($timeout) {
return {
restrict: 'AC',
link: function(_scope, _element) {
$timeout(function(){
_element[0].focus();
}, 0);
}
};
});
使用
<input name="theInput" auto-focus>
我们使用超时来让dom中的东西呈现,即使它是零,它至少会等待它-这种方式也适用于模态和其他东西
你可以创建一个指令,将焦点集中在postLinking的装饰元素上:
angular.module('directives')
.directive('autoFocus', function() {
return {
restrict: 'AC',
link: function(_scope, _element) {
_element[0].focus();
}
};
});
然后在你的html中:
<input type="text" name="first" auto-focus/> <!-- this will get the focus -->
<input type="text" name="second"/>
这适用于情态动词和ng-if切换的元素,而不适用于ng-show,因为postlinks只发生在HTML处理中。
很容易. .试试这个
html
<select id="ddl00">
<option>"test 01"</option>
</select>
javascript
document.getElementById("ddl00").focus();
Mark和Blesh有很好的答案;然而,Mark的回答有一个Blesh指出的缺陷(除了实现复杂之外),我觉得Blesh的回答在创建一个专门向前端发送焦点请求的服务时存在语义错误,而实际上他所需要的只是一种延迟事件的方法,直到所有指令都在侦听。
这就是我最后做的事情,从Blesh的答案中窃取了很多,但保持了控制器事件和“after load”服务的语义分离。
这允许控制器事件很容易被其他事情所吸引,而不仅仅是聚焦一个特定的元素,还允许只在需要时才引起“after load”功能的开销,在很多情况下可能不是这样。
使用
<input type="text" focus-on="controllerEvent"/>
app.controller('MyCtrl', function($scope, afterLoad) {
function notifyControllerEvent() {
$scope.$broadcast('controllerEvent');
}
afterLoad(notifyControllerEvent);
});
源
app.directive('focusOn', function() {
return function(scope, elem, attr) {
scope.$on(attr.focusOn, function(e, name) {
elem[0].focus();
});
};
});
app.factory('afterLoad', function ($rootScope, $timeout) {
return function(func) {
$timeout(func);
}
});
你也可以使用angular内置的jqlite功能。
angular.element (.selector) .trigger(重点);