Reusable custom angularJS directive to display error or success

In my earlier following posts I have talked about custom exception handling and custom angularJS logger service.

To complement these services, I have developed a custom angularJS directive that is used to display status of actions executed in the application. The directive uses isolated scope for it to be reusable as long as the data source to display status and errors follows the format dictated by it.

Custom AngularJS Directive To Display Error or Success status


WebPortal.directive("tradeActionStatus", ['$timeout',function ($timeout) {
var directiveObject = {
    restrict: 'E',
    scope: {
        actionStatus: '='
    },
    templateUrl: PortalSettings.baseUrl + "angular/Templates/ActionStatus.html",
    link: function (scope, element, attrs) {
        var blurIt = function () {
            scope.hideIt = true;
        };
        scope.blurAfter = attrs["blurAfter"];
        if (scope.blurAfter) {
            scope.blurAfter = parseFloat(scope.blurAfter);
            if (scope.blurTime > 0) {
                $timeout(blurIt, scope.blurAfter * 1000);
            }
        }
    }
};
return directiveObject;
}]);

The custom directive uses isolated scope. The scope has actionStatus property bound to attribute on the directive. The users of the directive must provide status data through this attribute. Following snippet shows how this directive is used.


<div class="col-xs-12">
 <trade-action-status 
      data-action-status="status" 
      data-blur-after="2"></trade-action-status>
</div>

The directive offers a second attribute blurAfter to allow to hide the status panel disappear after specified number of seconds.

Data model definition

Following c# class is used as ActionStatus model that is returned when a WebApi is executed.

        
public class ActionStatus
{
    public ActionStatus()
    {
        Errors = new List<ActionError>();
    }
    public int StatusCode { get; set; }
    public string Message { get; set; }
    public string Details { get; set; }
    public ICollection<ActionError> Errors { get; set; }
}

Template file for directive UI

As you can see from directive implementation that is uses templateUrl to get the user interface template for displaying status information.


 <div ng-show="actionStatus" ng-if="!hideIt">
 <div ng-class="{'alert alert-success':actionStatus.StatusCode==200, 
    'alert alert-danger':actionStatus.StatusCode !=200}">
 <div class="panel-body">
         {{actionStatus.Message}}
 <div ng-show="actionStatus.Errors">
 <ul>
 <li ng-repeat="error in actionStatus.Errors">{{error.Reason}}</li>
             </ul>
         </div>
     </div>
 </div>
</div>

I hope this provides you some useful information in implementing a reusable angularJS directive.

comments powered by Disqus

Blog Tags