Monday, August 18, 2014

AngularJS validation messages using ngMessages

As you know AngularJS provides several validation attributes such as required, minimum length, pattern etc which simplify the form validation. But showing the validation messages is a big pain (up to version 1.3). We have to write a bunch of ng-if statements to show the proper error message and this get much more complex than the actual validation.

AngularJS reduces this pain of showing validation messages using ngMessages directive. The ngMessages internally works like a switch statement, it will accept an object and based on the values of this object, ngMessages shows the corresponding message. This can be better demonstrated with the below example:

Let’s say we have the below javascript object

    var messages = {
        required: false,
        minlength: false,
        maxlength: false,
        email: true
    }

As you see this object contains a set of properties out of which email is true. Now we will pass this object to the ngMessages directive as mentioned below

<div ng-messages='vm.messages'>
    <div ng-message="required">This field is required</div>
    <div ng-message="minlength">This field is too short</div>
    <div ng-message="maxlength">This field is too long</div>
    <div ng-message="email">This field has an invalid email address</div>
</div>

As expected ngMessages shows the message corresponding to the email as it’s value is true.
In the actual scenario, instead of our custom object, we will pass the angular’s error attribute as shown below:

<div ng-messages='loginForm.username.$error>

The ngMessages based on the angular’s error attribute shows the message. Here is the full code on using the ngMessages directive

    <div class="form-group" ng-class="{'has-error': loginForm.username.$invalid && vm.isFormSubmitted(loginForm.username) }">
        <label for="username" class="col-sm-2 control-label">Username</label>
        <div class="col-sm-3">
            <input type="text" class="form-control" name="username" ng-model="vm.model.UserName" required autofocus>
            <div class="error-messages" ng-messages="loginForm.username.$error" ng-if="vm.isFormSubmitted(loginForm.username)">
                <div ng-message="required">Username is required</div>
            </div>
        </div>
    </div>

In my next blog I will go more detail on the above code. For now let’s assume ngMessage directive acts like a switch statement.


Saturday, August 16, 2014

Prevent FOUC in AngularJS using resolve

Flash of Unstyled Content (FOUC) happens in the below scenarios
  • When the application is initially loading and AngularJS has not loaded yet
  • When AngularJS is fetching data from the server

In the above scenarios user may see flashes of pages without data or see data slowing getting loaded. Hence for better user experience we should avoid this.

As you know AngularJS provides ng-cloak to handle FOUC and this is needed when the AngularJS is not loaded (first scenario above).

For the second scenario where we need avoid FOUC , Angular provides a mechanism when it is fetching data from the server. This is done using resolve feature. The resolve ensures that the controller and data is properly loaded before AngularJS binds the view. When we fetch data using resolve, Angular waits till the data is fetched and thereby avoiding FOUC.

Here is the sample code which utilizes resolve to fetch data from the server.

    $routeProvider
        .when("/contact", {
            templateUrl: "/app/contact/contact.html",
            controller: "contact",
            controllerAs: "vm",
            resolve: ['contactService', function (contactService) {
                return contactService.resolve();
            }]
        })

As you see resolve is used in the routing and here I am specify that the controller loading need to wait till the service fetches data from the server.

Tuesday, August 12, 2014

AngularJS http interceptor for DTO

In my single page applications I standardized data exchange between client side javascript framework (AngularJS) and a rest service (WebAPI) using a DTO. I am using the following DTO to properly encapsulate data from server to client. Please refer to my SPA DTO blog for more details.

public class AjaxModel<T>
{
    public bool Success { get; set; }
    public string Message { get; set; }
    public T Model { get; set; }
}

As you see, I defined a generic class which shuttles the data using generic object. In addition it also carries a boolean variable specifying whether the call is success or not and a message which can contain positive or negative message.

With this object I can send any type of data from the Web API to the client along with the status. The client on receiving this message can check the status before processing the data. But I want to preprocess this on the client so that I have generic code that process all responses from the server.

Angular’s interceptor in instrumental for my scenario. It enable me to intercept the http response from the server and preprocess it before my page gets the response. Here is my code which processes the http response from REST service

    function response(response) {
        //checking whether we got our AjaxModel
        if (response.data.hasOwnProperty("Success") && response.data.hasOwnProperty("Message") && response.data.hasOwnProperty("Model")) {
            if (response.data.Success === false) {
                //as needed show error message to the user
                //reject the response
                return $q.reject(response);
            }
            else {
                response.data = response.data.Model;
            }
        }

        // Return the response or promise.
        return response || $q.when(response);
    }

As you see I am checking the response from server and if the Success flag is true I am rejecting the response. This response will be captured using the error callback. Here is the client code which internally uses the interceptor

    return $http.get("/api/contact")
        .success(function (data) {
            service.model = data;
        })
    .error(function (data) {
        //process error if needed
    });

Using Angular’s interceptor we intercepted our http response and preprocessed it. In addition this we can use the interceptor to catch the request, request error and response error. Here is the code of this interceptor.

'use strict';
angular.module('appinterceptors').factory('WebAPIInterceptor', WebAPIInterceptor);
WebAPIInterceptor.$inject = ['$q'];

function WebAPIInterceptor($q) {

    return {
        request: request,
        requestError: requestError,
        response: response,
        responseError: responseError
    };

    //request success
    function request(config) {

        // Return the config or promise.
        return config || $q.when(config);
    }

    //request error
    function requestError(rejection) {

        // Return the promise rejection.
        return $q.reject(rejection);
    }

    // response success
    function response(response) {
        //checking whether we got our AjaxModel
        if (response.data.hasOwnProperty("Success") && response.data.hasOwnProperty("Message") && response.data.hasOwnProperty("Model")) {
            if (response.data.Success === false) {
                //as needed show error message to the user
                //reject the response
                return $q.reject(response);
            }
            else {
                response.data = response.data.Model;
            }
        }

        // Return the response or promise.
        return response || $q.when(response);
    }

    //response Error
    function responseError(rejection) {
        // Return the promise rejection.
        return $q.reject(rejection);
    }
}

For a working code of this interceptor please go to my GitHub or take a look at the Gist.

Saturday, August 2, 2014

Daily Time Management

As you all know time management is crucial for productivity. If time is properly managed we can do more work in a day. It also keeps us motivated as we achieve more and thus gives us satisfaction. In this blog I outline the time management technique I am following.

In order to effectively do time management we have to plan for every day and execute the plan effectively. Before we start, it is important to make a list of your daily recurring tasks, i.e., the set of tasks you do every day. This could include daily reflection, daily goal setting.

Every day at the end of the day we have do planning for the next day. Write down the list of activities that needs to done tomorrow. To this list add our daily recurring tasks. Also include tasks that are related to your goals. It is crucial that you have tasks that are related to your goals. If a task or activity is bigger than few hours try to split it into multiple smaller tasks.

Identifying the tasks one day earlier makes your brain think about it during the night. Also including tasks related to your goals ensures that you don’t forget about your goals and makes you work towards it.

On the next morning, set aside some time to again go over the tasks you created. This time prioritize those tasks. During this prioritization you can also add additional tasks you missed yesterday. While prioritizing the tasks the tasks, bucket all your tasks under A, B, C, D, E.

A is the first priority. These are tasks you have to complete in that day. Once we complete the A tasks depending on the time constraints we can take up the B & C tasks. If there is not enough time, these tasks can be pushed to next day.

D means delegate. Delegate as many taks as you can. Delegating tasks gives you time which you can focus on you’re a tasks. E means eliminate. Directly eliminate those tasks which are not needed and don’t value add

Once you prioritize your tasks focus only on A tasks and execute those tasks before the end of the day. If you needed within A, you can categorize the tasks as A1, A2 etc.


If we can follow this approach we can easily reach our goals within a short period. 

Revealing Module pattern in AngularJS

If you have worked with object oriented programming you are aware that there are private and public methods and properties. But that concept completely lacks in JavaScript. Wouldn’t be nice if JavaScript also has the same private and public concepts.

Revealing Module pattern encapsulates the JavaScript classes (functions) and reduces the spaghetti code. This pattern sometimes looks like an interface. This pattern ensures that all the methods and variables are private by default until they are explicitly exposed as public.  This pattern provides a very good structure to the JavaScript code and makes it is easier to understand and use.

I will first show a javascript code that we typically use for an Angular controller and then refactor it with Revealing Module pattern.

Let’s assume that we are working on a Contact page, where user enters First Name and Last Name of a Contact and clicks save button to save the contact.

Here is the code we typically use for this scenario

angular.module('app').controller('contact', function($scope) {

    $scope.firstName = "Praval";
    $scope.lastName = "Pattam";

    $scope.save = function () {
        alert('contact saved');
    }
});

Let’s rewrite the same controller code using the Revealing Module Pattern:

angular.module('app').controller('contact', function() {

    var vm = {
        firstName: "Praval",
        lastName: 'Pattam',
        save: save
    };

    return vm;

    function save() {
        alert('contact saved');
    }
});

As you see in the above code, from the first line we know what all this controller does. This is similar to the interface we see in object oriented languages. With this pattern and ControllerAs functionality we can eliminate the $scope from our code.


This Revealing Module Pattern is my favourite pattern for structuring the JavaScript code as it provides a clean interface. For my other patterns and demos please check out my GitHub site.