在AngularJS中,“Angular的方法”是什么?
更具体的要求:
当打开一个模态时,将焦点设置在这个模态内预定义的<input>上。 每次<input>变得可见时(例如,通过单击某个按钮),将焦点设置在它上。
我尝试用自动对焦来实现第一个要求,但这只在Modal第一次打开时有效,并且只在某些浏览器中有效(例如在Firefox中它不起作用)。
在AngularJS中,“Angular的方法”是什么?
更具体的要求:
当打开一个模态时,将焦点设置在这个模态内预定义的<input>上。 每次<input>变得可见时(例如,通过单击某个按钮),将焦点设置在它上。
我尝试用自动对焦来实现第一个要求,但这只在Modal第一次打开时有效,并且只在某些浏览器中有效(例如在Firefox中它不起作用)。
当前回答
你可以创建一个指令,将焦点集中在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处理中。
其他回答
下面的指令对我来说很管用。对输入使用相同的autofocus html属性。
.directive('autofocus', [function () {
return {
require : 'ngModel',
restrict: 'A',
link: function (scope, element, attrs) {
element.focus();
}
};
}])
首先,关注1.1的路线图是一种正式的方式。同时,您可以编写一个指令来实现设置焦点。
其次,在一个项目变得可见之后设置焦点,目前需要一个变通方法。只是用$timeout延迟对元素focus()的调用。
因为同样的控制器-修改- dom问题存在于焦点,模糊和选择,我建议有一个ng-target指令:
<input type="text" x-ng-model="form.color" x-ng-target="form.colorTarget">
<button class="btn" x-ng-click="form.colorTarget.focus()">do focus</button>
Angular线程在这里:http://goo.gl/ipsx4,更多细节在这里:http://goo.gl/4rdZa
下面的指令将在你的控制器中创建一个由ng-target属性指定的.focus()函数。(它也创建了.blur()和.select()。)演示:http://jsfiddle.net/bseib/WUcQX/
不需要创建自己的指令,可以简单地使用javascript函数来完成一个焦点。
这里有一个例子。
在html文件中:
<input type="text" id="myInputId" />
在javascript文件中,例如在控制器中,你想要激活焦点的地方:
document.getElementById("myInputId").focus();
我发现其他一些答案过于复杂,而你真正需要的只是这个
app.directive('autoFocus', function($timeout) {
return {
restrict: 'AC',
link: function(_scope, _element) {
$timeout(function(){
_element[0].focus();
}, 0);
}
};
});
使用
<input name="theInput" auto-focus>
我们使用超时来让dom中的东西呈现,即使它是零,它至少会等待它-这种方式也适用于模态和其他东西
你可以使用下面的指令,在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页面渲染时。