我注意到我在很多控制器上添加了一些代码,以监听事件并执行某些操作。这个差不多:
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]();
};
});
}
};
});
想法?
使用隔离范围,您可以通过单向数据绑定传递函数。假设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();
});
});
}
};
});