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

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.