1

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.

2
  • Would you mind posting a fiddle so we'd see the exact problem? Commented May 10, 2015 at 8:33
  • better make a service for the alert, not a directive, because you are showing it dynamically after each post added Commented May 10, 2015 at 8:56

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

0

Per the Bootstrap documentation (emphasis mine):

… Closing an alert removes it from the DOM.

Because it's removed from the DOM it will not show up again...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.