Javascript 使用$timeout删除数组中的元素无法正常工作
指令通知应在5秒后删除“自身”。但是,有些元素会丢失,有些元素会被多次删除。标识符属性对于每个通知都是唯一的。谢谢你的帮助 工厂Javascript 使用$timeout删除数组中的元素无法正常工作,javascript,arrays,angularjs,angularjs-directive,Javascript,Arrays,Angularjs,Angularjs Directive,指令通知应在5秒后删除“自身”。但是,有些元素会丢失,有些元素会被多次删除。标识符属性对于每个通知都是唯一的。谢谢你的帮助 工厂 angular.module('AdS').factory('notificationFactory', function () { var notificationFactory = {}; notificationFactory.notifications = []; notificationFactory.identifier =0; notificationF
angular.module('AdS').factory('notificationFactory', function () {
var notificationFactory = {};
notificationFactory.notifications = [];
notificationFactory.identifier =0;
notificationFactory.add = function(note){
if(typeof note!=='undefined'){
notificationFactory.identifier++;
note.identifier = notificationFactory.identifier;
notificationFactory.notifications.push(note);
}
}
notificationFactory.delete = function (note) {
if(typeof note!=='undefined'){
for(var i =0;i<notificationFactory.notifications.length;i++){
if(notificationFactory.notifications[i].identifier==note.identifier){
notificationFactory.notifications.splice(i,1);
}
}
}
return "";
}
notificationFactory.getNotifications = function () {
return notificationFactory.notifications;
}
return notificationFactory;
});
html
您可以使用一个对象,该对象的唯一标识符指向您的便笺,而不是为
notificationFactory.notifications使用数组,如下所示:
notificationFactory.notifications = {};
notificationFactory.add = function(note) {
if (typeof note!=='undefined') {
notificationFactory.identifier++;
notificationFactory.notifications[notificationFactory.identifier] = note;
}
}
notificationFactory.delete = function (note) {
if(typeof note!=='undefined'){
notificationFactory.notifications[notificationFactory.identifier] = null;
}
return "";
}
另外,在您的指令中,您似乎是通过html注入notificationFactory。这是非常不寻常的,典型的工厂注射方式如下:
angular.module('AdS').directive('siteNotification', [
'$timeout',
'notificationFactory',
function ($timeout, notificationFactory) {
...
}
我能看到以不同方式执行此操作的唯一原因是,如果您希望能够将不同类型的工厂注入到指令中。将通知作为notificationFactory.notifications添加到数组中。[notificationFactory.identifier]=注意-有效。谢谢,伙计。虽然我意识到我有打字错误。。。很高兴知道它有效,但我仍在更新答案。
notificationFactory.notifications = {};
notificationFactory.add = function(note) {
if (typeof note!=='undefined') {
notificationFactory.identifier++;
notificationFactory.notifications[notificationFactory.identifier] = note;
}
}
notificationFactory.delete = function (note) {
if(typeof note!=='undefined'){
notificationFactory.notifications[notificationFactory.identifier] = null;
}
return "";
}
angular.module('AdS').directive('siteNotification', [
'$timeout',
'notificationFactory',
function ($timeout, notificationFactory) {
...
}