Search code examples
angularjsangularjs-directiveangularjs-scope

Alert directive not showing after it has been rendered once


I have a directive to display an alert message every time a post call succeeds/fails. The alert for the first post always succeeds but if I close the alert, and trigger another post the alerts don't show anymore.

Some code below:

Include tag in html

<alert message="notification"></alert>

Directive

app.directive("alert", function(){
        return{
            restrict: 'EA',
            templateUrl: "alert.html",
            replace: false,
            transclude: false,
            scope: {
                message: "=",
                close: "&"
            },
            link: function(){

            }
        };
    });

Template

<div class="alert alert-{{message.type}}" ng-show="message.text">
    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
    <div>{{message.text}}</div>
</div>

UPDATE: http://plnkr.co/edit/mECmQNSgW0EdXZGPmkNx?p=preview

Any thoughts?

Thanks in advance.


Solution

  • Instead of using data-dismiss="alert" you can have your close button call the close function. The close function can then clear the notifications since you have $scope.notification in the isolated scope as scope.message:

    var app = angular.module('app', []);
    
    app.controller('AlertDemoCtrl', function($scope) {
      $scope.notification = {};
    
      $scope.alertNotif = function() {
        $scope.notification.type = "error";
        $scope.notification.text = "demo text";
      };
    });
    
    
    app.directive("alert", function() {
      return {
        restrict: 'EA',
        template: '<div class="alert alert-{{message.type}}" ng-show="message.text">' +
          '<button type="button" class="close" ng-click="close()" aria-hidden="true">&times;</button>' +
          '<div>{{message.text}}</div>' +
          '</div>',
        replace: false,
        transclude: false,
        scope: {
          message: "=",
          close: "&"
        },
        link: function(scope) {
          scope.close = function() {
            scope.message = {};
          }
        }
      };
    });
    <!DOCTYPE html>
    <html ng-app="app">
    
    <head>
      <!-- jQuery -->
      <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
    
      <!-- Latest compiled and minified CSS -->
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    
      <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.js"></script>
      <script src="script.js"></script>
    </head>
    
    <body>
      <div ng-controller="AlertDemoCtrl">
        <button ng-click="alertNotif()">test</button>
        <alert message="notification"></alert>
      </div>
    </body>
    
    </html>