Custom angularJS directive with isolated scope and custom template

Some time back I wrote a custom ASP.Net control that was used to display current server time and a user's connection latency with server. When I migrated the application to AngularJS, I ended up writing a custom directive that shows latency information to the user. In this post I will share that custom AngularJS directive.

custom angular directive

Some of the key elements in this directive are:

  • Restricting the directive to be applied as element
  • Using isolated scope for directive
  • Using custom template to replace directive element

PortalApp.directive('connectionLatency', [
    function() {
        var directiveObj = {
            scope: {
                lastLatency: '=',
            template:"<span class='bigger-160'>..</span>",
            link: function(scope, element, attr, ctrl) {
                scope.$watch('lastLatency', function (val) {
                    if (val > 3000) {
                        scope.css = 'red';
                    else if (val > 1000) {
                        scope.css = 'orange';
                    } else {
                        scope.css = 'green';
        return directiveObj;

The directive binds to last latency value through two way binding with lastLatency value. It puts a watch on this value. This way when latency value changes, the directive updates template HTML to display appropriate text with css class that reflects the appropriate conditions for user's connectivity.

comments powered by Disqus

Blog Tags