我有一个Angular应用,使用angularJS v1.7和angular-ui-router。在每个控制器中,我都有onkey事件,并且在index.html中有一个模式菜单。我的问题是模式显示时,我需要在控制器中删除onkey事件并在模式中添加onkey事件。我的应用程序中有很多控制器。
index.html
<body ng-app="app-demo">
<a ui-sref="home">Go to HOME</a>
<ui-view></ui-view>
<div ng-controller="vt" style="position: fixed; right: 0; top: 0;">
<div>Modal show: {{ vt }}</div>
</div>
<script>
app.controller('vt', function($scope,$rootScope) {
$scope.vt = false;
function onKeyupVT() {
$scope.vt = !$scope.vt;
$scope.$apply();
}
document.addEventListener('keyup',onKeyupVT);
});
</script>
</body>
home.html
<div ng-controller="app-home">
<h1>Home</h1>
<button ng-click="goToSubPage()">Click me to view sub list.</button>
</div>
<div ui-view="list-1"></div>
<div ui-view="list-2"></div>
list-1.html
<div ng-controller="list-1">
This is List - 1
</div>
homeController.js
app.controller('app-home', function($scope,$state) {
$scope.goToSubPage = function() {
$state.go('list-1');
}
function onKeyup() {
console.log('Home');
}
document.addEventListener('keyup',onKeyup);
});
app.controller('list-1', function($scope,$stateParams) {
function onKeyup() {
console.log('list-1');
}
document.addEventListener('keyup',onKeyup);
});
我该怎么办。我是angularJS的新手。
答案 0 :(得分:0)
一种方法是创建一个服务来委托keyup
事件:
app.service("keyupDelegate", function() {
this.target = new EventTarget();
this.disableDispatch = false;
document.addEventListener("keyup", keyupHandler);
function keyupHandler(event) {
if (!this.disableDispatch) {
this.target.dispatchEvent(event);
};
}
});
然后每个视图控制器都可以将其用作目标:
app.controller('app-home', function(keyupDelegate) {
// ...
function onKeyup() {
console.log('Home');
}
keyupDelegate.target.addEventListener('keyup',onKeyup);
this.$onDestroy(function() {
keyupDelegate.target.removeEventListener("keyup",onKeyup);
});
});
模态控制器可以在激活时禁用调度:
app.controller("modal",function(keyupDelegate) {
//...
keyupDelegate.disableDispatch = true;
this.$onDestroy(function() {
keyupDelegate.disableDispatch = false;
});
});