The deletion of elements in an array using $timeout is experiencing issues with functionality

After 5 seconds, the directive notification should automatically delete itself. However, there seems to be an issue where some elements are missed and others get deleted more than once. Each notification has a unique identifier property. Thank you for any assistance provided.

Factory

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

Directive

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>

Answer №1

Instead of utilizing an array for storing notifications in

notificationFactory.notifications
, consider using an object where the unique identifier points to each note like this:

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

Furthermore, within your directive, it appears that you are injecting notificationFactory through HTML, which is quite unconventional. The typical approach to inject your factory is as shown below:

angular.module('AdS').directive('siteNotification', [
    '$timeout',
    'notificationFactory',
    function ($timeout, notificationFactory) {
        ...
    }

The only valid reason I can think of for deviating from this norm is if you intend to have the flexibility to inject a different type of factory into your directive.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Passing data between pages in Node.js

My current project involves creating a web service using node.js. In this setup, I am utilizing curl to send POST data to my index.js application. The index.js app processes the received data and I need it to then route the output to various pages based on ...

Error message: calling for member 'GetSum' in a test, which is of pointer type 'Test*' (perhaps you intended to use '->' instead?)

Currently, I am exploring how to create an array using a Class. In my attempt, I utilized malloc to generate a ptr array named "test". However, upon trying to utilize the function associated with the value in the array, I encountered an error message: "er ...

The alert box is not displaying, only the text within the tags is visible

Trying to implement an alert message for logged-in users. A successful login will trigger a success message, while incorrect username or password will display an error. function showMessage(response) { if (response.statusLogged == "Success login") { ...

Expect for a variety of Observables to finish at different times

I am faced with the challenge of extracting data from an API that is paginated, and unfortunately, I cannot determine the total number of pages in advance. However, I can identify when I have reached the last page. My goal is to develop a function that ret ...

A React component created in a class cannot effectively update its state when using a functional component to pass

I'm currently working on a React project that involves both a Class component and a Functional Component. In my Class component, I have a function that updates the name in its state. The issue arises when I try to pass this function as a property to t ...

Drag and Drop in Angular with Dragula - Trigger Confirmation on Drop Event

I need to implement a confirm modal dialog (UI Kit) when an element is dragged into a new bag using angular 1.4.8 and angular-dragula. If the user clicks ok, the process should continue, but if they click NO, the element should return to its original bag. ...

When utilizing the File System Access API, the createWritable() method functions perfectly within the console environment but encounters issues when executed

I've been diving into the File System Access API for an upcoming project and I'm struggling with using the createWritable() method. Specifically, I'm encountering issues with this line of code: const writable = await fileHandle.createWritab ...

I am not receiving the filtered data from the pagination directive

Hello everyone! I am currently utilizing the pagination directive from the following link: https://github.com/michaelbromley/angularUtils/tree/master/src/directives/pagination However, I am encountering a challenge with retrieving filtered data. Typicall ...

Gaining entry into a JSON object

I'm currently working on a web page that utilizes API data from the Breaking Bad website. I have received this data in JSON format, but I am struggling to figure out how to access only the objects where the "author" is "Walter White." Here is the data ...

Is it a CSS or Javascript quirk when a div can become the child of the div before it?

On every browser I've checked, the code in the html is exactly the same: <td class="bardisplay"> <div class="bar hot" /> <div class="bar cool" /> </td> However, in the debugger of each browser, including Chrome, the DOM ...

Which is quicker: making a jQuery GET request or using Angular's $http.get method

Recently, I came across an interesting observation while working on my angular app. I noticed that replacing $http.get calls with jQuery ajax calls significantly boosted the speed of the application. This made me wonder if jQuery calls are actually faster ...

Enhancing security with Mongoose's bcrypt for asynchronous password setting and saving

I've defined a mongoose schema that includes a method to set a password using bcrypt: UserSchema.methods.setPassword = function (password) { bcrypt.hash(password, saltRounds).then(function (hash) { this.hash = hash; }); }; When creating a us ...

Tips for utilizing the <base> element in HTML5 for selective anchor tags

I only have one base tag in the head section of my HTML document, and there are two anchor tags with different URLs as shown below: <!DOCTYPE html> <html lang="en"> <head> <base href="https://www.youtube.com"/> </head> &l ...

Using " " to split a name into two lines is not being recognized

My issue involves the display of tab names in two lines within multiple tabs. You can view the demonstration here. I attempted to use the \n character while setting the tab name but it was not recognized. Any suggestions on how to achieve this? Here ...

Sorting an array in PHP based on a different index value

I am faced with the challenge of sorting two arrays simultaneously. The first array, $number, contains a list of numbers such as 1212, 340, 2310, 670, and 90. The second array, $cars, includes corresponding car names like "Volvo", "BMW", "Toyota", "Maruti" ...

Troubleshooting form errors with jQuery AJAX on form submissions

Below is a form that I have: <form name="frm_dcg" id="frm_dcg" method="post" enctype="multipart/form-data" action="" onsubmit="return validate_form();" > <div class="login-form"> <div class="sign-in-htm"> -----------other cod ...

React fails to respond to the .click() method

I believe the .click function originates from jQuery, but I came across it being used in pure JavaScript as well. This makes me wonder if I can utilize it in my React code too. The scenario where I want to incorporate it is as follows: keyUpFunction(even ...

Azure App Service for Mobile and Web applications

Currently, I am in the initial stages of assessing and designing the potential architecture for a Mobile App (using Xamarin) and a Web App (most likely using Angular). The Azure App Service appears to be a suitable option for hosting these services. Howeve ...

Is there a way to fetch data from Firebase to a website without relying on the use of a "get

I have a code where I need to input the ID to retrieve the rest of the data from the table. However, I want to display all the data in all tables without the need for a button click to get them row by row. For example, this is how it looks in my Firebase ...

Is there a way to determine if a table cell contains overflowing text compared to another cell?

https://i.sstatic.net/IYafA.png Is there a way to detect if the content of the fourth td overflows from the second td? I am looking for a method to determine which td has overflowed text and identify which td's text is overflowing. What approach ca ...