我有一个类似的html按钮:
<button autofocus role="button" ng-disabled="something.$invalid">{{ Continue }}</button>
该按钮最初是禁用的,因此自动焦点属性没有任何效果。我想要发生的是,当按钮被启用时,我想马上将焦点放在按钮上。
我怎样才能做到这一点?
编辑:如下所述,指示监视一个值,然后将焦点设置为元素是解决这一问题的一种方法。我试图创建与下面相同的指令,但是焦点似乎没有被设置好。
发布于 2015-04-21 13:20:51
啊我让它起作用了。我必须将focus函数设置为在使用$timeout的事件循环的一个周期之后触发,如下所示:
.directive('focusToMe', function($timeout) {
return {
restrict: 'A',
compile: function() {
var directiveName = this.name;
return function(scope, elem, attrs) {
scope.$watch(attrs[directiveName], function(newVal, oldVal) {
if (newVal) {
$timeout(function() {
elem[0].focus();
}, 0)
}
})
}
}
}
})
发布于 2015-04-20 19:34:56
正如评论中提到的那样,指令对此是有益的。下面的代码将观察模型并传递给它,并在元素变为真时将重点放在元素上。
module.directive('focusToMe', function($parse) {
return {
restrict: 'A',
compile: function() {
var directiveName = this.name;
return function(scope, element, attrs) {
scope.$watch(attrs[directiveName], function(newVal, oldVal) {
if (newVal) {
element.focus();
}
})
}
}
}
});
然后将其添加到按钮元素中:
<button autofocus role="button" ng-disabled="something.$invalid" focus-to-me="something.$invalid">{{ Continue }}</button>
https://stackoverflow.com/questions/29761468
复制