监听事件的指令
Directive to listen on event
我注意到我在很多控制器上添加了一些代码来侦听事件并执行某些操作。差不多是这样:
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();
});
});
}
};
});
我注意到我在很多控制器上添加了一些代码来侦听事件并执行某些操作。差不多是这样:
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();
});
});
}
};
});