桃花长相依
打开一个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));
});
}
};}]);柱塞$timeout似乎是需要给模式时间来渲染。“2”每当<Input>变为可见时(例如,通过单击某个按钮),请将焦点设置在它上。创建一个本质上类似于上面的指令。观察某些作用域属性,当它变为真时(在ng-click处理程序中设置它),执行element[0].focus()..根据您的用例,您可能需要或不需要$timeout:<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:我见过一些人使用我最初的隔离作用域指令,然后在嵌入式输入字段(即模态中的输入字段)中遇到问题。没有新作用域(或者可能是新的子作用域)的指令应该可以减轻一些痛苦。因此,上面我更新了答案,使之不使用隔离作用域。以下是原来的答案:1.的原始答案,使用隔离作用域: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();
});
}
});
}
};});柱塞.使用隔离作用域的2.的原始答案:<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;
//});
}
});
}
};});柱塞.因为我们需要在指令中重置触发器/FocusInput属性,所以‘=’用于双向绑定。在第一个指令中,“@”就足够了。还请注意,当使用‘@’时,我们将触发器值与“true”进行比较,因为@总是产生字符串。