在我下面的 angular 应用程序中,我有多行 myelement
(input
标签上的 angular 指令包装器)。有时我需要聚焦/选择/突出显示其中一个,样式中的 .selected
类就是这样做的。
在以下应用程序中,除了焦点到 input
标签外,一切正常,该标签需要受 css 类 selected
的限制。 IE。任何元素具有 selected
类,相应的 input
标签都应该被关注。我怎么能做到这一点?
<!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>
最佳答案
考虑以下示例。它使用了现在推荐的 AngularJS 的 component
特性(自 v1.5 起)。该示例非常简单,因此您可以轻松了解正在发生的事情以及如何将其应用到您的元素中。
JavaScript
class MainController {
constructor() {
this.focused = true;
}
}
class MyElementController {
constructor($element) {
this.$element = $element;
}
$onChanges(changes) {
if (changes.focused.currentValue === true) {
this.$element[0].getElementsByTagName('input')[0].focus();
}
}
}
const myElementComponent = {
bindings: {
focused: '<'
},
controller: MyElementController,
template: `<input type="text">`
};
angular
.module('app', [])
.controller('MainController', MainController)
.component('myElement', myElementComponent);
HTML
<body ng-app="app" ng-controller="MainController as vm">
<my-element focused="vm.focused"></my-element>
</body>