加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

将AngularJS中的文档级键事件绑定到特定路由/控制器的正确方法是

发布时间:2020-12-17 17:43:54 所属栏目:安全 来源:网络整理
导读:我有一个单页应用程序可以打开一个库.我想仅在图库打开时绑定文档级别键盘事件(用于键盘库控件),即.当路线匹配时 .when('/reference/:galleryId/:imageId/',{ templateUrl: '/partials/gallery.htm',controller: 'galleryController',controllerAs: 'referen
我有一个单页应用程序可以打开一个库.我想仅在图库打开时绑定文档级别键盘事件(用于键盘库控件),即.当路线匹配时

.when('/reference/:galleryId/:imageId/',{ templateUrl: '/partials/gallery.htm',controller: 'galleryController',controllerAs: 'reference' })

当我离开这条路线时,我想解开它.

可能有问题的一件事是,我阻止在同一个图库中的图像之间重新加载视图:

.run(['$route','$rootScope','$location',function ($route,$rootScope,$location) {
    var original = $location.path;
    $location.path = function (path,reload) {
        if (reload === false) {
            var lastRoute = $route.current;
            var un = $rootScope.$on('$locationChangeSuccess',function () {
                $route.current = lastRoute;
                un();
            });
        }
        return original.apply($location,[path]);
    };
}])

演示(点击“Fotografie”打开图库)
http://tr.tomasreichmann.cz/

Angular wiz救援?

感谢您的时间和精力

解决方法

您可以将keyup事件绑定到控制器构造函数中的$document,然后在控制器的$scope被销毁时解除绑定.例如:

.controller('galleryController',function ($scope,$document) {
  var galleryCtrl = this;

  function keyupHandler(keyEvent) {
    console.log('keyup',keyEvent);
    galleryCtrl.keyUp(keyEvent);

    $scope.$apply(); // remove this line if not need
  }

  $document.on('keyup',keyupHandler);
  $scope.$on('$destroy',function () {
    $document.off('keyup',keyupHandler);
  });

  ...
});

当视图变为非活动状态时,将不会遗留任何内容.

如果您觉得在控制器中执行此操作是不对的,可以将其移动到自定义指令中并将其放在视图的模板中.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读