Showing posts with label AngularJS. Show all posts
Showing posts with label AngularJS. Show all posts

Wednesday, November 9, 2016

AngularJS - JavaScript - Client Side error logging

Usually for ServerSide logging we can use many error logging tools (For ex: elmah, log4net etc.,) to log errors into database and email. But for client side JavaScript framework we should include some extra code or some tools available (for ex: JSNLog etc.,). Here am going to explain how custom we do that,

First create JavaScript file "errorlog.js" and copy paste below code,

var errorLoggingServerURL = "Error/Log";

function logErrorToServer(ex, stack) {
    if (ex == null) return;

    if (stack == null && ex.stack != null) stack = ex.stack;

    // format output
    var out = ex.message != null ? + ": " + ex.message : "JavaScript Exception";
    if (stack != null) out += "\n  at " + stack.toString();

    // send error message
        type: 'POST',
        url: errorLoggingServerURL,
        data: { message: escape(out) }


Function.prototype.trace = function () {
    var trace = [];
    var current = this;
    while (current) {
        current = current.caller;
    return trace;

Function.prototype.signature = function () {
    var signature = {
        name: this.getName(),
        params: [],
        toString: function () {
            var params = this.params.length > 0 ?
                "'" + this.params.join("', '") + "'" : "";
            return + "(" + params + ")"
    if (this.arguments) {
        for (var x = 0; x < this.arguments.length; x++)
    return signature;

Function.prototype.getName = function () {
    if (
    var definition = this.toString().split("\n")[0];
    var exp = /^function ([^\s(]+).+/;
    if (exp.test(definition))
        return definition.split("\n")[0].replace(exp, "$1") || "anonymous";
    return "anonymous";

window.onerror = function (msg, url, line) {
    if (arguments != null && arguments.callee != null && arguments.callee.trace)
        logErrorToServer(msg, arguments.callee.trace());


In AngularJS, we can have custom logging as follows,

To override AngularJS default logging and to write custom logging use as below,

 app.factory('$exceptionHandler', function () {
        return function (exception, cause) {
            //Javascript Error log will catch this

Or to use both angularJS default logging and custom logging use as below

//Exception log decorator
 $provide.decorator('$exceptionHandler', ['$delegate', function ($delegate) {
    return function (exception, cause) {
     $delegate(exception, cause);

In Server Side, we can receive the Ajax call and use any logging tool to log error, For ex, here am using Elmah to log error, it uses MVC action controller and using logging as custom class named JavaScriptException

public class ErrorController : Controller
public void Log(string message)
                .Raise(new JavaScriptException(HttpUtility.UrlDecode(message)));


Saturday, August 13, 2016

AngularJS - Bootstrap Datepicker Model Formatter

I have case to show datepicker for textbox, we can simply bind DateString field to textbox and update. But if we use BootStrap uibDatePicker then it requires to format as Date object before binding to ngModel.

So to resolve this issue, i have created directive to format ngModel value before binding and also parse back to string before updating to controller.

To check how to create BootStrap datepicker check here 

Just create Directive as follows

    app.directive('datePickerModelFormatter', function () {
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function (scope, element, attr, ngModel) {
                function dateToString(dateValue) {
                    if (dateValue != null) {
                        var dateTimeToReturn = new Date(dateValue);
                        return dateTimeToReturn.toISOString();
                    return dateValue;

                function stringToDate(stringValue) {
                    if (stringValue != null) {
                        var newOffsetDateTime = new Date(stringValue);
                        return new Date(newOffsetDateTime.setMinutes(newOffsetDateTime.getMinutes() + newOffsetDateTime.getTimezoneOffset()));
                    return stringValue;



and on HTML just include this model

  <p class="input-group">
          <input type="text" class="form-control" uib-datepicker-popup="{{format}}" ng-model="dt" is-open="popup1.opened" datepicker-options="dateOptions" ng-required="true" close-text="Close" alt-input-formats="altInputFormats" date-picker-model-formatter />
          <span class="input-group-btn">
            <button type="button" class="btn btn-default" ng-click="open1()"><i class="glyphicon glyphicon-calendar"></i></button>

Thats it, it will convert to DateObject and Return back as StringObject (ISOString format)

Tuesday, June 28, 2016

AngularJS - BootStrap Popover Directive

In some cases we need to show some popover as tooltip or as dialog

Here am going to use BootStrap Popover, this plugin is part of BootStrap.js file or we can include spearately. For more information about that read here 

I am going to create simple popover

Step 1; Create your html pages, include BootStrap js files, AngularJS, JQuery basic setups

Step 2: Here is what I created directive to make PopOver work with AngularJS, add this directive to your application

var app = angular.module('appModuleName');

app.directive('popover', ['$compile',function ($compile) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
                html: true,
                title:  attrs.popoverTitle || "Header",
                content: function () {
                    return $compile($("#" + attrs.popoverContent).html())(scope);
                placement: attrs.popoverPlacement || "top"


Step 3: In your HTML, just use this directive and pass attributes

<input type="button" popover popover-title="Header Text" popover-content="popover-content-id" popover-placement="top"/>

Step 4: Here you can pass your Title, ContentId, placement (Top, Bottom, Right, Left) etc.  This popover-content-id is div with contents

  <div id="popover-content-id" class="hide">
Some content here..

Friday, May 6, 2016

AngularJS - Multiselect Drop down

In some cases, we need to create multi select dropdown. With AngularJS directive it is very easier to implement

Okay, let me first show basic multi select dropdown without any angularJS

<select data-ng-model="model" data-ng-options="value as name for item in itemlist" multiple>
    <option value="" style="color:gray;">-Select Item-</option>

Here we used simple Select element with multiple attribute. It allows you to select multiple items from dropdown. But drawback is, we should use Ctrl key to select multiple items and also style is not that much easier to customize.

To resolve these dependencies, we can choose AngularJS directive as solution.

app.directive('multiSelectDropDown', function () {
        return {
            restrict: 'AE',
            scope: {
                model: '=',
                options: '=',
                optionsName: '@',
                optionsValue: '@',

            template: "<div class='btn-group dropdown' style='width:100%'>" +
             "<input type='text' value='{{model.toString()}}' data-toggle='dropdown' class='dropdown-toggle' placeholder='Click to select' disabled>" +
             "<button class='btn btn-small dropdown-toggle' data-toggle='dropdown'><span class='caret'></span></button>" +
                     "<ul class='dropdown-menu' style='width:100%'  aria-labelledby='dropdownMenu'>" +
                         "<li><a data-ng-click='selectAll()'><i class='glyphicon glyphicon-ok'></i>  Select All</a></li>" +
                         "<li><a data-ng-click='deselectAll();'><i class='glyphicon glyphicon-remove'></i>  Deselect All</a></li>" +
                         "<li class='divider'></li>" +
                         "<li data-ng-repeat='option in options'>" +
                         "<a data-ng-click='setSelectedItem()'><span class=\"{{isChecked(option) ? 'glyphicon glyphicon-ok' : ''}}\"></span>&nbsp;{{option[''+optionsName+'']}}&nbsp;</a>" +
                         "</li>" +
                     "</ul>" +
            controller: function ($scope) {

                $scope.selectAll = function () {
                    $scope.model = [];
                    $scope.options.forEach(function (option, index) {

                $scope.deselectAll = function () {
                    $scope.model = [];

                $scope.setSelectedItem = function () {
                    var selected = this.option;
                    if ($scope.model == undefined || $scope.model == null)
                        model = [];

                    if (_.contains($scope.model, selected[$scope.optionsValue])) {
                        $scope.model = _.without($scope.model, selected[$scope.optionsValue]);
                    } else {

                    return $scope.model;

                $scope.isChecked = function (selected) {
                    if ($scope.model == undefined || $scope.model == null)
                        $scope.model = [];

                    if (_.contains($scope.model, selected[$scope.optionsValue])) {
                        return true;
                    return false;


This directive you can include into your AngularJS application as directive

 var app = angular.module('yourAppName');

In HTML, we can call this directive simply like below

 <multi-select-drop-down model="model" options="itemlist" options-name="name" options-value="value "></multi-select-drop-down>

This requires BootStrap css file, Glyphicons to make work.