Directives are markers on a DOM element that tell AngularJS's HTML compiler to attach a specified behavior to that DOM element or even transform the DOM element and its children. Better define all Global controllers in Directives. Ex: Warning message, alert etc. I am going to explain how to display a flash message using directive concept in Angular js.
I have explained the same using Angular 4 as well, check this link for that.
Directive
'restrict' option is used to
'A' - Attribute (Use it as <div flashmessage>) 
'E' - Element (Use it as <flashmessage>)
'C' - Class. (Use it as <div class="flashmessage">)
'M' - Comment (Use it as <!- directive: flashmessage -> )
 
angular.module('yourmodule').directive('spFlash',
function() {
 return {
  restrict : 'A',
  replace : true,
  template : '<div class="flash row-fluid">'
 
 + '<div class="flash-inner span4 offset4 alert alert-success"
 
 data-ng-repeat="msg in successMsg">{{msg}}</div>'
 
 + '</div>',
 // If you are using twitter bootsrtap along with angular
 //then you can use this classes span4 ,offset4 ,alert etc 
 //or you can define your own css for better look an feel.
 
 link : function($rootScope, scope, element, attrs) {
  $rootScope.$watch('successMsg', function(val) {
   if (val.length) {
    update();
   }
  }, true);
   
 function update() {
  $('.flash')
   .fadeIn(500).delay(3000)
   .fadeOut(500, function() {
   $rootScope.successMsg.splice(0);
  });
 }
   }
  };
 }
);
 
Watch concept :- Watch is a powerful feature of angular js. “$watch” concept in Angular is to observe the changes on the data of the scope from the controller. That is controller can add a listener on an attribute of its scope.
Controller
Just copy the one line of code and display flash message anywhere in your application.
angular.module('sampleproject').controller( 'sampleController',
function ($rootScope, $scope ,$location )
{
 $scope.samplefunction = function(){
  //Flash message
  $rootScope.successMsg.push('success');
 };
});
CSS
You can write your own css for better look an feel.
.flash {
 position: absolute;
 top: auto;
 left: 0;
 width: 100%;
 display: none;
 }
.flash-inner {
  your styles ...
 }
Include this on header or where you need to show the message
<div data-sp-flash></div>
Related Posts
1. Communicate with controllers in angular js
2. Rating Stars using angular js Directive concept
5. Filtering concept in angular js
6. Save highchart as binary image
I am newbie !!
ReplyDeleteCan you put your code to jsfiddle.net ?
Please !
could you please put this code in jsfiddle.net with example??
ReplyDelete