如何将焦点设置在输入字段上?在AngularJS中,聚焦于输入场的“角度方式”是什么?更具体的要求:当模态,则将焦点设置为预定义的<input>在这个模态里面。每次<input>变得可见(例如,通过单击某个按钮),将焦点设置在上面。我试图达到第一个要求带着autofocus,但这只在第一次打开Modal时才起作用,而且只在某些浏览器中才起作用(例如,在Firefox中,它不起作用)。任何帮助都将不胜感激。
3 回答
桃花长相依
TA贡献1860条经验 获得超8个赞
打开一个Modal时,将焦点设置在此Modal内预定义的<Input>上。
Name: <input type="text" focus-me="shouldBeOpen">
app.directive('focusMe', ['$timeout', '$parse', function ($timeout, $parse) {
return {
//scope: true, // optionally create a child scope
link: function (scope, element, attrs) {
var model = $parse(attrs.focusMe);
scope.$watch(model, function (value) {
console.log('value=', value);
if (value === true) {
$timeout(function () {
element[0].focus();
});
}
});
// to address @blesh's comment, set attribute value to 'false'
// on blur event:
element.bind('blur', function () {
console.log('blur');
scope.$apply(model.assign(scope, false));
});
}
};}]);
“2”每当<Input>变为可见时(例如,通过单击某个按钮),请将焦点设置在它上。
element[0].focus()
<button class="btn" ng-click="showForm=true; focusInput=true">show form and
focus input</button><div ng-show="showForm">
<input type="text" ng-model="myInput" focus-me="focusInput"> {{ myInput }} <button class="btn" ng-click="showForm=false">
hide form</button></div>app.directive('focusMe', function($timeout) {
return {
link: function(scope, element, attrs) {
scope.$watch(attrs.focusMe, function(value) {
if(value === true) {
console.log('value=',value);
//$timeout(function() {
element[0].focus();
scope[attrs.focusMe] = false;
//});
}
});
}
};});更新7/2013
Name: <input type="text" focus-me="{{shouldBeOpen}}">app.directive('focusMe', function($timeout) {
return {
scope: { trigger: '@focusMe' },
link: function(scope, element) {
scope.$watch('trigger', function(value) {
if(value === "true") {
$timeout(function() {
element[0].focus();
});
}
});
}
};});<button class="btn" ng-click="showForm=true; focusInput=true">show form and focus input</button><div ng-show="showForm"> <input type="text" focus-me="focusInput"> <button class="btn" ng-click="showForm=false">hide form</button></div>
app.directive('focusMe', function($timeout) {
return {
scope: { trigger: '=focusMe' },
link: function(scope, element) {
scope.$watch('trigger', function(value) {
if(value === true) {
//console.log('trigger',value);
//$timeout(function() {
element[0].focus();
scope.trigger = false;
//});
}
});
}
};});- 3 回答
- 0 关注
- 772 浏览
添加回答
举报
0/150
提交
取消
