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 = {
            restrict:'E',
            scope: {
                lastLatency: '=',
                css:'@'
            },
            replace:true,
            template:"<span class='bigger-160'>..</span>",
            link: function(scope, element, attr, ctrl) {
                scope.$watch('lastLatency', function (val) {
                    element.removeClass(scope.css);
                    if (val > 3000) {
                        scope.css = 'red';
                        element.html('High');
                    }
                    else if (val > 1000) {
                        scope.css = 'orange';
                        element.html('Med');
                    } else {
                        scope.css = 'green';
                        element.html('Low');
                    }
                    element.addClass(scope.css);
                });
            }
        };
        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

Search

Social

Weather

19.3 °C / 66.7 °F

weather conditions Clear

Monthly Posts

Blog Tags