定义一个指令,并使其$ watch一个属性/触发器,以便它知道何时集中该元素:
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.’ 每当变为可见(例如,通过单击某些按钮)时,将焦点放在它上面。
创建一个基本上与上述指令相似的指令。观察一些scope属性,当它变为true(在ng-click处理程序中设置)时,执行executeelement[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;
//});
}
});
}
};
});
:我已经看到一些人使用我原来的隔离范围指令,然后在嵌入的输入字段(即模态中的输入字段)方面遇到问题。没有新作用域(或可能新的子作用域)的指令应减轻某些痛苦。因此,以上我更新了不使用隔离范围的答案。以下是原始答案:
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;
//});
}
});
}
};
});
柱塞。
由于我们需要在指令中重置trigger / focusInput属性,因此“ =”用于双向数据绑定。在第一个指令中,“ @”就足够了。还要注意,当使用“ @”时,我们将触发值与“ true”进行比较,因为@始终会产生字符串。