Erik van de Ven
Erik van de Ven

Reputation: 4975

Angular hide alert message again after x seconds or page change

I'm quite new to angular, now I was able to show an alert message when someone requests a new password, from 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('unkown user id');
    }

    model.resetted = true;


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

    authorizedTracker.addPromise( deferred.promise)

    return deferred.promise;
};

So if resetted is true, the message will show up, see 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 is sent to your e-mail
</div>

But now I want to hide the alert after x amount of seconds, or if the user clicks to another page. How is that possible? Any solution?

Upvotes: 6

Views: 18450

Answers (3)

Eduard Void
Eduard Void

Reputation: 2714

For angular2+ users:

You should add timeout to the method witch is showing alert:

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

where hideAlert makes a logic needed to hide an alert and X is number of miliseconds

the idea behind this is to start counting X miliseconds until this.hideAlert is called

arrow function is needed to keep original context (be able to use this as we are used to - pointing to parent class for example)

Upvotes: 1

Polochon
Polochon

Reputation: 2219

you should use the $timeout service (symilar to the window.setTimeout in native javascript).

In your code you should add the following code

...
model.resetted = true;

$timeout(function() {

    model.resetted = false;

}, xxx)//replace xx by the amount of milisecond you want

here is an example, hope it will help you http://plnkr.co/edit/Qt39x5Xo5JhP61QHYLwO?p=preview

Upvotes: 6

bmleite
bmleite

Reputation: 26870

To close after X seconds use the $timeout service.

model.resetted = true;

$timeout(function() {
  model.resetted = false;
}, X); // X in milliseconds

Upvotes: 2

Related Questions