AngularJS指令:如何使用超时隐藏警报

AngularJS Directive: How do I hide the alert using timeout?

本文关键字:隐藏 超时 何使用 指令 AngularJS      更新时间:2023-09-26
  • 昨天,我开始为我的项目编写notification directive
  • 我在stackoverflow AngularJS上问了一个问题:警报没有出现,在浏览了文档和视频后,我能够建立一个基本的通知指令http://plnkr.co/edit/uqSB1gIz6XEmJfC8zHNb?p=preview

我想要什么

像任何其他应用程序一样,当警报出现时,它们会在一秒钟左右后隐藏,我正在试图找到一种在一秒钟后隐藏警报的方法,但不知道如何进行

非常感谢任何帮助

更新

根据@Derek的回答,我可以实现超时
http://plnkr.co/edit/uqSB1gIz6XEmJfC8zHNb?p=preview

通常,我会用一个数组来实现通知,它将新的通知推送到堆栈上,然后设置$timeout,从数组中删除该特定元素。在渲染方面,您只需要使用ng中继器。

然而,在您的情况下,如果您想保留现有的指令,您可以通过添加一个链接函数并设置$timeout来删除元素来实现此功能。

app.directive('notification', function($timeout){
  return {
     restrict: 'E',
     replace: true,
     scope: {
         ngModel: '='
     },
     template: '<div class="alert fade" bs-alert="ngModel"></div>',
     link: function(scope, element, attrs){
         $timeout(function(){
             element.remove();
         }, 5000);
     }
  }
});

我已经更新了@dayderer创建的plunker,以显示多个警报并自动隐藏。如果有人想定制多个警报,可以看看这个Plunker Link

一半的代码与@DerekR相同,我只对其进行了定制

var app = angular.module('myApp', ['$strap.directives']);
app.directive('notification', function($timeout){
  return {
    restrict: 'E',
    replace: true,
    scope: {
      ngModel: '='
    },
    template: '<div class="alert fade" bs-alert="ngModel"></div>',
    link: function(scope, element, attrs) {
      $timeout(function(){
        element.hide();
      }, 3000);
    }
  }
});
app.controller('AlertController', function($scope){
    $scope.message = {
      "type": "info",
      "title": "Success!",
      "content": "alert directive is working pretty well with 3 sec timeout"
    };
    $scope.alerts = [];
    $scope.addAlert = function(index) {
      $scope.alerts.push(
          {
            "type": "info",
            "title": "Success!" + index,
            "content": "alert "  + index + " directive is working pretty well with 3 sec timeout"
          }
      )
    }
});