监听事件的指令

问题描述 投票:0回答:1

我注意到我在很多控制器上添加了一些代码,以监听事件并执行某些操作。这个差不多:

  document.addEventListener("resume", function(e){
    $scope.doSomething();
  }, false);

我意识到到处都是相同的代码是不干净的,唯一改变的是$scope.doSomething()

我想将其添加为指令,以便可以有类似以下内容:

<div on-resume="doSomething()">
</div>

我尝试过此操作(但不起作用):

.directive('onResume', function(){ 
   return {
      restrict: 'A'
      link: function(scope, elem, attr, ctrl) {
         elem.bind('resume', function(e) {
            fnName = attributes["onResume"];
            scope.$apply(function(){ 
              scope[fnName]();
            };
         });
      }
   };
});

想法?

javascript angularjs angularjs-directive dom-events
1个回答
1
投票

使用隔离范围,您可以通过单向数据绑定传递函数。假设doSomething在您的父范围内定义为一个函数,那么它将与您包含的HTML一起使用。

.directive('onResume', function() {
  return {
    restrict: 'A',
    scope: {
      onResume: '&'
    },
    link: function(scope, elem, attr, ctrl) {
      elem.bind('resume', function(e) {
        scope.$apply(function() {
          scope.onResume();
        });
      });
    }
  };
});
© www.soinside.com 2019 - 2024. All rights reserved.