I'm studying Angular and want to develop my own notification alert. This is what I done, I like it and it's working like a charm but I think that it can be improved:
- Do I need to use it in conduction with a service? If yes, how?
- It will be better if it become an E (element)?
- I needed to put style="display: none;" (see: html code) so it does not appear when the page is loaded and I think that it's not the best way, what to do?
- How to show and hide more classy, with some animation? CSS? Add/Remove [custom] class?
- Any hint and tip will be welcome!
This is the directive:
myApp.directive('notification', ['$timeout', function ($timeout) {
return {
restrict: 'A',
controller: ['$scope', function ($scope) {
$scope.notification = {
status: 'hide',
type: 'success',
message: 'Welcome! It\'s yet another angular alert ;)'
};
}],
link: function(scope, elem, attrs) {
// watch for changes
attrs.$observe('notification', function (value) {
if (value === 'show') {
// shows alert
$(elem).show();
// and after 3secs
$timeout(function () {
// hide it
$(elem).hide();
// and update the show property
scope.notification.status = 'hide';
}, 3000);
}
});
}
};
}]);
This is the HTML:
<div class="alert alert-{{notification.type}}" style="display: none;" role="alert" data-notification="{{notification.status}}">{{notification.message}}</div>
A simple example on how to use:
<button id="submit" name="submit" class="btn btn-default" type="submit" ng-click="notification.status = 'show'; notification.message = 'Oh yeah!'; notification.type = 'info';">Show</button>
This is the Plunkr