2015-10-15 54 views
-1

指令通知应在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> 

回答

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) { 
     ... 
    } 

我能看到的唯一的理由这样做不同的方式是,如果你希望能够注入不同类型的工厂到您的指示。

+0

将notification作为notificationFactory.notifications添加到数组中。[notificationFactory.identifier] = note - working。谢了哥们。 – Rennos

+0

虽然实际上已经意识到我有一个错字...很高兴知道它的工作,但我仍然在更新答案。 –