javascript x 秒或页面更改后,角度再次隐藏警报消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25309265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:21:22  来源:igfitidea点击:

Angular hide alert message again after x seconds or page change

javascriptangularjs

提问by Erik van de Ven

I'm quite new to angular, now I was able to show an alert message when someone requests a new password, from our app:

我对 angular 很陌生,现在当有人从我们的应用程序请求新密码时,我能够显示一条警报消息:

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:

因此,如果重置为 true,则会显示该消息,请参见下文:

html:

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?

但现在我想在 x 秒后隐藏警报,或者如果用户点击到另一个页面。这怎么可能?有什么解决办法吗?

回答by Polochon

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

您应该使用 $timeout 服务(类似于本机 javascript 中的 window.setTimeout)。

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

这是一个例子,希望它能帮助你 http://plnkr.co/edit/Qt39x5Xo5JhP61QHYLwO?p=preview

回答by bmleite

To close after X seconds use the $timeoutservice.

要在 X 秒后关闭,请使用该$timeout服务。

model.resetted = true;

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