AngularJS 中 点击按钮 使焦点在指定文本框中
自定义指令
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));
});
}
};
}]);
html
Name: <input type="text" focus-me="isFocusedOn">
focusOn: <button ng-click="setfocusOn()"></button>
js中
$scope.isFocusedOn=false;//是否将将焦点放在该处
/*
* 放焦点
*/
$scope.setfocusOn=function(){
$scope.isFocusedOn=true;
}
参考:
How to set focus on input field? https://stackoverflow.com/questions/14833326/how-to-set-focus-on-input-field