Issue
I was just wondering if there is a way to define conditional event listener i.e. is there a way to listen for the event only if some condition is met.
I think I am asking for an unorthodox stuff, or there is a way already exists which I am oblivious of.
Example:
Let 'lastRepeat'
be an event emitted by the directive when ng-repeat ends.
app.controller('ctrl',function($scope){
$scope.$on('lastRepeat', callback); // Here the callback will be called every time lastRepeat event is emitted by the directive
});
But what I am looking for is something like this (This is what I have thought of, solution need not use same approach):
app.controller('ctrl',function($scope){
function foo(){
if(bool)
$scope.$on('lastRepeat', callback); // Problem listening like this is that a listener is created everytime foo is called and condition is met and hence we end up having multiple listeners
}
)};
Basically I want to avoid this multiple creation of listeners. Is there a way I can store this listener like a variable and listen only if some condition is met.
Solution
How about:
app.controller('ctrl', function($scope) {
var condition = false;
var callback = function () {};
$scope.$on('lastRepeat', function() {
if (!condition) return;
callback();
});
});
Answered By - tasseKATT
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.