Trong ứng dụng góc sau đây của tôi, tôi có nhiều hàng myelement
(trình bao bọc chỉ thị góc trên input
). Tại một thời điểm tôi cần phải tập trung/chọn/làm nổi bật một trong số đó, .selected
lớp trong các phong cách làm điều đó.Lớp liên kết góc của phần tử với phần tử focus
Trong ứng dụng sau, mọi thứ hoạt động tốt ngoại trừ việc tập trung vào thẻ input
cần được giới hạn bởi lớp css selected
. I E. bất kỳ phần tử nào có lớp selected
cần phải tập trung vào thẻ input
tương ứng. Làm thế nào tôi có thể đạt được điều đó?
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<style>
.container {
display: flex;
flex-direction: column;
width: 600px;
}
.notebook {
display: flex;
justify-content: center;
}
.cell {
margin: 5px;
padding: 5px;
}
.selected {
border-style: solid;
border-color: green;
border-width: 1px;
border-left-width: 5px;
}
</style>
</head>
<body ng-app="myApp">
<div ng-controller="ListController as listctrl" class="notebook">
<div class="container">
<myelement ng-repeat="i in listctrl.list"
ng-click="listctrl.selected = $index"
ng-class="{selected : listctrl.selected === $index}"
class="cell"></myelement>
</div>
</div>
<script type="text/javascript">
angular
.module('myApp',[])
.controller('ListController', function($scope) {
var listctrl = this;
listctrl.list = [];
listctrl.selected = 0;
listctrl.addCell = function() {
var x = listctrl.list.length;
listctrl.list.push(x);
listctrl.selected = listctrl.list.length - 1;
}
listctrl.addCell();
$scope.$on('add', function (event, message) {
$scope.$apply(listctrl.addCell);
});
$scope.$on('keyUp', function(event) {
$scope.$apply(function(){
listctrl.selected = listctrl.selected - 1;
});
});
$scope.$on('keyDown', function(event) {
$scope.$apply(function(){
listctrl.selected = listctrl.selected + 1;
});
});
})
.directive('myelement', function($rootScope){
return {
template: '<input style="width: 95%"></input>',
restrict: 'E',
link: function (scope, element, attrs) {
var inputTag = element[0].children[0];
inputTag.focus();
element.on('keydown', function(event) {
if (event.keyCode === 13 && event.shiftKey) {
$rootScope.$broadcast('add');
} else if (event.keyCode === 38) {
$rootScope.$broadcast('keyUp');
} else if (event.keyCode === 40) {
$rootScope.$broadcast('keyDown');
}
});
},
controller: function ($scope) {
}
};
})
</script>
</body>
</html>
Không được ng-class = "{selected: listctrl.selected === $ index}" có dấu "?" ở giữa lựa chọn và listctrl.selected vì nó là một ternary? Hay tôi đọc sai. –
@Dream_Cap nó không phải là một thứ ba, chỉ là một đối tượng theo nghĩa đen – Phil
Bạn không thể sử dụng một cái gì đó như 'element.hasClass ('selected') && inputTag.focus()'? Bạn có thể cần đặt 'ưu tiên' của chỉ thị thành một cái gì đó lớn hơn' 0' để chức năng liên kết sau của nó chạy sau 'ngClass' – Phil