Conceal the Angular alert message automatically after a specified number of seconds or when the page

I recently started working with Angular and managed to implement an alert message for password reset requests in our app:

Usermodel:

.service('userModel', ['$q', '$http', 'authorizedTracker', function($q, $http, authorizedTracker) {
    this.passwordreset = function(token) {

    var deferred = $q.defer();

    $http({
        method: 'GET',
        url: '/reset/'+token
    })

    .then(function(response) {

    if (!_(response.data).has('user')) {
        deferred.reject('unknown user id');
    }

    model.resetted = true;


    }, function(error) {
        deferred.reject(error.data.message);
    });

    authorizedTracker.addPromise( deferred.promise)

    return deferred.promise;
};

If the resetted value is true, the success message will be displayed as shown below:

html:

<!-- Succes-->
<div class="alert alert-success animated fadeInDown" ng-cloak  ng-show="userModel.resetted">
    <strong><i class="icon-attention"></i>Success!</strong> New password has been sent to your email
</div>

Now I am looking for a way to automatically hide the alert after a certain amount of time or if the user navigates to another page. How can I achieve this? Any suggestions?

Answer №1

Consider utilizing the $timeout service, which is similar to window.setTimeout in native javascript.

To implement this in your code, consider adding the following snippet:


...
model.resetted = true;

$timeout(function() {

    model.resetted = false;

}, xxx)//replace xx with the desired time in milliseconds

For a visual example, you can refer to this link: http://plnkr.co/edit/Qt39x5Xo5JhP61QHYLwO?p=preview

Answer №2

If you want to automatically close something after a certain amount of time, you can utilize the $timeout service.

model.refreshed = true;

$timeout(function() {
  model.refreshed = false;
}, Y); // Y represents the time duration in milliseconds

Answer №3

For those utilizing angular2+:

It is recommended to include a timeout within the method that displays alerts:

setTimeout(() => this.hideAlert(), Y);

where hideAlert contains the necessary logic to conceal an alert and Y represents the number of milliseconds

The concept here is to initiate a countdown of Y milliseconds before invoking this.hideAlert

The arrow function is essential for preserving the original context (enabling the use of 'this' in its typical context, such as referring to the parent class)

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

Loop through the elements of one array using the indexes from a second array

Hey there! I need help with the following code snippet: let names = ["josh", "tony", "daniel"]; let arrayplaces = ["30", "60", "90"]; names.forEach((elem, indexed) => { const num2 = arrayp ...

AngularJS allows for the uploading of files in each row of a table

Currently, I have implemented a table where users can enter details in each row and view the corresponding image. This functionality has been achieved using AngularJS. Although I managed to get it working for the first row after much effort, I am now faced ...

There is a lack of 'Access-Control-Allow-Origin' header - Issue encountered while making Food2Fork API request using AJAX

Our team has just embarked on our first project, and I've encountered a roadblock while conducting API testing. Specifically, I am struggling to generate a successful access control header. Is there anyone who can provide assistance in troubleshooting ...

Explore an object to locate an element along with its parent

Here is an example of an object: $scope.categories = [ { value: 'One', id: 1, childs: [ { value: 'Two', id : 2, childs: [ { v ...

Preventing Javascript Pop Up from automatically jumping to the top of the page

Upon clicking a button (refer to image below and take note of the scroll bar position), a div pop up is triggered through Javascript. View image: https://docs.google.com/file/d/0B1O3Ee_1Z5cRTko0anExazBBQkU/preview However, when the button is clicked, the ...

Receive a notification when the div element stops scrolling

I am attempting to replicate Android's expandable toolbar within an Angular component. My HTML code appears as follows: <div (scroll)="someScroll($event)"> <div class="toolbar"></div> <div class="body"></div> </d ...

After encountering a character with CSS, begin a new line

I have a CSV spreadsheet with data that looks like this: <p>Features:• first feature• second feature• third feature• fourth feature• and so on (the total number of features is variable)</p> I want each feature to display on a new li ...

Trigger a click event on a third-party webpage that is embedded within an Angular application

In the process of developing my angular application, I found a need to incorporate a graph visualization tool. To achieve this, I utilized the HTML <embed> tag and successfully integrated the graph into my application. Now, my objective is to enable ...

CoffeeScript equivalent of when the document is loaded

Recently, I've been delving into Coffeescript for my web application, but I'm encountering a frustrating issue. The methods are not being called until I manually reload the page. I suspect that the missing piece may be the $(document).ready(func ...

Reduce code length for generating DOM fragment with jQuery

I'm currently working on generating a tree of elements that will be used as an input for JsTestDriver unit tests. I've got some code to create this tree which involves using Document Object Model methods in JavaScript. I'm wondering if there ...

The website's responsive design functions flawlessly when viewed on a desktop browser or mobile-simulator for Safari and Mozilla Firefox. However, when accessed on an actual smartphone using Android or iOS

I've been experimenting with different lines of code, but I'm struggling to pinpoint the error as my code functions on a desktop and should also work on mobile devices... <meta name="viewport" content="width=device-width, initial-scale=1, max ...

Struggling to retrieve form data in Node.js, Express, and MongoDB?

How can I properly access the data submitted through a form using Node and Express, in order to store it in MongoDB? When I try to retrieve the NAME field, I get "undefined", and for DATA I get "[object Object]". In my MongoDB database, the _id is genera ...

VueJS, when used in conjunction with Vuetify, might require an extra loader to handle scoped css

While attempting to compile my VueJS code using webpack, I encountered an error with the following code: <template> <v-app-bar app color="blue" flat height="100px"> <v-img class="mx-2" contain max-height="80" m ...

Browser encountering HTTP response that has been shorted extensively

When making an HTTP post request using axios, I am encountering an issue where the body of the response is a large 4MB string. axios({ method: 'POST', url: url, data: data, headers : headers, }) .then(function (response) { co ...

Issues encountered when trying to execute npm start: "The function this.htmlWebpackPlugin.getHooks is not recognized."

My background in web development is weak, and I'm facing a challenging situation. I had to take over the work of a colleague who left, and now I'm trying to finish the site we were working on. Since then, I've been learning about web develop ...

Data table created with functional components is not refreshing when columns are added or removed, which are stored in the state as an array of objects

I’ve been working on setting up a datatable with a checkbox dropdown feature to add or remove columns from the table. Everything is functioning properly, except for one issue – the table is not refreshing unless I click on one of the header titles. At ...

Using npm link with Webpack results in eslint errors

I have a multi-package project setup, where I have one JavaScript package that depends on a TypeScript library. Initially, I was using Sinopia and had to reinstall the TypeScript library every time I made changes to it. Then I discovered npm link and thoug ...

How can I showcase a Google donut chart using an array of data in a React application?

I have created a doughnut chart that is supposed to take an array as data. However, when I input the array, nothing shows up on the chart. How can I create a chart with array data? sum.js ... const arr = []; arr.push({ key: capitalizeEachFirst ...

How can I modify this section of the code in Google Script to retrieve all columns?

My question is, how can I modify this code to fetch all columns from the array instead of just [0,1,2,3] Here is the line of code in question: const new_table = [0,1,2,3].map(x => make_row_from_col(this_table, x)).join('\n'); Using obje ...

Sort data by various categories using Vue.js

I need help filtering my JSON data based on multiple categories using Vuejs, specifically with Vue 3 and collect.js. Here's the template I'm working with: <select v-model="selectedCategory" multiple> <option :value="n ...