我使用的是angular-web-notification (https://github.com/sagiegurari/angular-web-notification),我已经建立了一个工厂,以避免每次我想要显示它时复制粘贴。我的工厂是这个
module.registerFactory('browserNotification', function($rootScope, webNotification) {
return {
show: function(title, body, callback) {
webNotification.showNotification(title, {
body: body,
icon: 'img/icon.png',
onClick: callback,
autoClose: 5000 //auto close the notification after 4 seconds (you can manually close it via hide function)
}, function onShow(error, hide) {
if (error) {
console.log('Unable to show notification: ' + error.message);
} else {
console.log('Notification Shown.');
setTimeout(function hideNotification() {
console.log('Hiding notification....');
hide(); //manually close the notification (you can skip this if you use the autoClose option)
}, 5000);
}
});
}
}
})
正如您所看到的,我传递给show() 3个变量,其中一个是onClick函数的回调,以便在单击通知时执行操作。事情是,我想关闭通知一旦点击,但我不知道如何,因为隐藏()函数不存在于回调函数执行的上下文中。例如,在我的控制器中,我有这个
browserNotification.show('Test title', 'Test body', function() {
hide();
alert('Entro al callback!');
});
这里,hide()不存在。那么,我如何从回调函数中关闭通知呢?
这就成功了!
module.registerFactory('browserNotification', function($timeout,webNotification) {
return {
show: function(title, body, callback) {
var snd = new Audio('audio/alert.mp3');
snd.play();
//the timeout is to sync the sound with the notification rendering on screen
$timeout(function() {
var hideNotification;
webNotification.showNotification(title, {
body: body,
icon: 'img/icon.png',
onClick: function onNotificationClicked() {
callback();
if (hideNotification) {
hideNotification();
}
},
autoClose: 5000 //auto close the notification after 4 seconds (you can manually close it via hide function)
}, function onShow(error, hide) {
if (!error) {
hideNotification = hide;
}
});
}, 150);
}
}
});