您的位置:首页 > Web前端 > AngularJS

Angular解决输入框由禁用状态转可用状态自动获取焦点失效问题

2016-10-01 20:23 766 查看
有时为了方便操作,我们会为输入框设置默认焦点。而且会设置输入权限,会禁止用户输入。

但是当从禁止输入切换为可输入的时候,输入框却不能设置焦点了。

原因的话,我看了一下,估计是当我们改变输入框绑定的值得时候,输入框并没有切换状态,还是禁用状态,所以我们无法设置焦点,就是执行顺序的问题。

上代码吧,写个指令,设置输入框焦点。

<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="UTF-8">
<title></title>
<script src="jquery.js"></script>
<script src="angular.js"></script>
<script>
angular.module("app", [])
.controller("ctrl", function($scope) {
$scope.data = [{
name: "aaa",
type: "string"
}, {
name: "bbb",
type: "int"
}, {
name: "ccc",
type: "float"
}];

$scope.init = function() {
$scope.dim = $scope.data[0];
}

$scope.changeDim = function(i){
$scope.dim = i;
}

})
.directive("setFocus", function(){
return {
scope:{
ngModel:"="
},
link:function(scope, element, attrs){
scope.$watch("ngModel", function(n, o){
element.focus();
})
}
}
})
</script>
</head>

<body ng-init="init()" ng-controller="ctrl">
<ul>
<li ng-repeat="item in data" ng-click="dim = item">
<a ng-click="changeDim(item)">{{item.name}}</a>
</li>
</ul>
<input type="text" id="name" ng-disabled="dim.type == 'string'" ng-model="dim.name" set-focus>
</body>

</html>


效果:



此文档的作者:justforuse

Github Pages:justforuse
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐