Angular解決輸入框由禁用狀態轉可用狀態自動獲取焦點失效問題
阿新 • • 發佈:2018-12-30
有時為了方便操作,我們會為輸入框設定預設焦點。而且會設定輸入許可權,會禁止使用者輸入。
但是當從禁止輸入切換為可輸入的時候,輸入框卻不能設定焦點了。
原因的話,我看了一下,估計是當我們改變輸入框繫結的值得時候,輸入框並沒有切換狀態,還是禁用狀態,所以我們無法設定焦點,就是執行順序的問題。
上程式碼吧,寫個指令,設定輸入框焦點。
<!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>
效果: