使用$ timeout删除数组中的元素无法正常工作

时间:2015-10-15 02:21:48

标签: javascript arrays angularjs angularjs-directive

指令通知应在5秒后删除“本身”。但是有些元素会被遗漏,有些元素会被删除多次。标识符属性对于每个通知都是唯一的。谢谢你的帮助。

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;
});

指令

angular.module('AdS').directive('siteNotification', [
'$timeout',
function ($timeout) {
    return {
        restric: "E",
        templateUrl: "/Templates/htmlBits/notification.html",
        scope: {

            note:"=",
            center:"="
        },
        link: function (scope, element, attrs) {  
        $timeout(function () {           
                scope.center.delete(scope.note);

            }, 5000);



            scope.delete=function(note){

                scope.center.delete(note);
            }



        }
    };
}

]);

HTML

 <site-notification ng-repeat="not in notificationCenter.notifications track by $index" center=notificationCenter note=not ></site-notification>

1 个答案:

答案 0 :(得分:0)

不是使用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) {
        ...
    }

我能看到以不同方式做到这一点的唯一原因是,如果您希望能够在指令中注入不同类型的工厂。