听取事件的指示

时间:2015-05-21 19:16:11

标签: angularjs javascript-events angularjs-directive

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

SELECT a.WBS_ELEMENT_ID as [WBS Element],
a.WBS_ELEMENT_DESC as [WBS Element Desc],
a.UHC_INDUSTRY as [Industry],
a.UHC_SECTOR as [Sector],
a.UHC_DUNS_NUMBER as [UHC DUNS Number],
a.UHC_DUNS_NAME as [UHC DUNS Name],
a.PRIORITY_SUB_SECTOR as [Priority Sub Sector],
a.BUDGET_ALLOCATION as [Budget Allocation],
a.LAST_UPDATED_ON as [Last Updated]
FROM DimSectorPd a
WHERE a.wbs_element_id is not null

UNION ALL

SELECT ROW_NUMBER() OVER (ORDER BY a.wbs_element_desc) as [WBS Element],
a.WBS_ELEMENT_DESC as [WBS Element name],
a.UHC_INDUSTRY as [Industry],
a.UHC_SECTOR as [Sector],
a.UHC_DUNS_NUMBER  as [UHC DUNS Number],
a.UHC_DUNS_NAME as [UHC DUNS Name],
a.PRIORITY_SUB_SECTOR as [Priority Sub Sector],
a.BUDGET_ALLOCATION as [Budget Allocation],
a.LAST_UPDATED_ON as [Last Updated]
from dimsectorpd a where a.WBS_ELEMENT_ID is null

我意识到在任何地方都使用相同的代码并不干净,唯一改变的是 document.addEventListener("resume", function(e){ $scope.doSomething(); }, false);

我想将其添加为指令,以便我可以使用类似的内容:

$scope.doSomething()

我试过了(但它没有用):

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

思想?

1 个答案:

答案 0 :(得分: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();
        });
      });
    }
  };
});