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

情到浓时终转凉″ 提交于 2019-12-02 19:33:20

Generally I would implement notifications with an array, that pushes new notifications onto the stack, then sets a $timeout that removes that particular element from the array. On the rendering side you would just use an ng-repeater.

However in your case, if you want to keep your existing directive you could accomplish this functionality by just adding a linking function and setting a $timeout to remove the element.

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

I have updated plunker created by @daydreamer to show multiple alerts and hide automatically. If anybody wants to customized multiple alerts have a look at this Plunker Link

Half of the code same as @DerekR, I have only made customization to it

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"
          }
      )
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!