Link function is best way in custom directives to manipulate DOM. It takes three attributes as input (scope, element, attribute) in sequence
scope: its local scope object of directive.
element: html element on which directive is used.
attribute: it gives access to all attributes used in element refered.
// on success call or similarly error, warning, info in controller
$scope.message={
text: "Saved Successfully",
type: "SUCCESS"
};
<user-info msg="message"> </user-info> //in html
var mainApp = angular.module("mainApp", []);
mainApp.directive('userInfo', function() {
var directive = {};
directive.restrict = 'E';
directive.scope = {
message : "=msg"
},
directive.link = function(scope, element, attributes) {
if(scope.message.type==='SUCCESS')
scope.message.text = 'SUCCESS: '+scope.message.text+' !';
else if(scope.message.type==='ERROR')
scope.message.text = 'ERROR: '+scope.message.text+' !';
else if(scope.message.type==='WARNING')
scope.message.text = 'WARNING: '+scope.message.text+' !'
else if(scope.message.type==='INFO')
scope.message.text = 'INFO: '+scope.message.text+' !'
element.on('click', function(event) { //on click of div pop-up will smoothly close
$(this).fadeOut();
});
},
directive.template = '<div ng-class={{message.type}}>'+ // one can create different bg-color as per type of message and width/height
'<div class="message-text">{{message.text}}<div>'+ //message text will be printed
'<div>';
return directive;
});