Implementing REST services in AngularJS using Restangular

Current web development trends are in favour of AngularJS. The framework is having its momentum and is one of the most popular choices for client side development frameworks. Personally, I like it a lot, it makes my job easier to jump start the web development projects quickly. It is also useful for hybrid mobile applications.

Another thing that has quite a momentum for some time now is implementation and consumption of REST services. REST as an architecture, although it makes things easier after implementation, is an architectural style which is very easy to get it wrong, despite most of the time what we need is simple GET/POST/PUT/DELETE requests.

Restangular is an AngularJS service which makes GET/POST/PUT/DELETE requests simpler and easier. The configuration is easier and can be done in several ways with different initiation settings. Let me try to put an easier demonstration on how to use Restangular on your site and how easy it is to make your AngularJS app consume RESTful service.

Configuration

The first thing to do is to reference restangular in your index.html (refer to official page for installation).

To configure restangular with your AngularJS app, in your app module definition file you configure restangular settings.

Now that we have restangular configured, we can make requests for resource like this:

Alternatively, we can also create services for our resources. For e.g. if I have a resource named students, I would create the service through these lines of code:

then I would add this service as a dependency to the controller that I want to use it in. With this simple service definition, I can now easily initiate GET/POST/PUT/DELETE requests through restangular.

Let us take some examples. We can read all students by requesting

or if I want to read the student with id 1234 I would request

Saving a student is also as easy as getting it

Restangular has the main request types GET/POST/PUT/DELETE almost ready made for us, but also it allows many things to be configured per our needs. We can make custom requests to custom methods, specify parameter names, and many other not so standard things. Please refer to restangular’s github page for detailed specifications.

As it makes RESTful api consumption so simple, currently it is one of my favorite parts of my AngularJS apps.

Implementing loading animation in AngularJS and jQuery

With the advancement of web development technologies, web application are closing the user experience gap with desktop applications very quickly. It is a very common practice to let the user know when the application is busy with a certain task, and one of the most common ways to do this is by showing a loading indicator or a spinning gif. This will let the user know that the application is working and he or she will not try to refresh or press other buttons until the task is finished.

To implement this, before the task is initiated at server, we must show our spinner or any loading animation we want to show, and then when the task is finished (successfully or unsuccessfully) hide the animation. I will show you how you can do it using jQuery and using AngularJS.

Implementing loading animation in jQuery

Let us start with the jQuery. I want to show a spinner whenever I post something to the server from the form, until I receive a response. Let us suppose we have a form like this:

and I have a div with a spinner gif img inside it somewhere in the html

At the beginning, I need to make this hidden, so you can put a css style display:none  or hide it using jquery or whatever way you like most.

There are several forms to determine how to show the spinner and hide it. One way is to bind to subscriptionForm ajaxSend and ajaxComplete events to show and hide the spinner respectively.

This will make the spinner show when a ajax request starts from that form and disappear when the request completes.

If it is the case that you need to make the spinner show for every ajax request made within the page, then you may need to bind the events to the DOM.

You can also make the spinner show as a modal dialog by applying a style like this and adding class ajax-loader to the spinner img element:

This will make the spinner show in a modal dialog and prevent the user from initiating any other requests before this one finishes.

Implementing loading animation in AngualarJS apps

The strategy for implementing the loading animation in AngularJS is little different and requires a bit of a setup. To catch the start and end of requests, in AngularJS we must create http interceptors for request and response. Interceptors will intercept requests before they are handed to the server so we can show our spinner and response before it is handed to the client so we can hide the spinner.

To get the interceptors, we need to register them through an anonymous factory  and inside request and response functions, we need to show and hide the div of spinner respectively.

Interceptors are a useful part of AngularJS which can be used to make several kinds of validations before a request is made or after a response is received (authentication validations, etc.), and one of the tasks we can put here is also to show and hide the spinner when a request has started and completed (please be aware that for the simplicity of the code, I have omitted functions which check for errors on requests).

To make the example more clear, I have create a sample interceptor demo in a Plunker, you may see it here http://plnkr.co/edit/hAg1T8sdsLq5c61iW97f?p=preview

This was a simple post to show you how is implementing loading animation in AngularJS and jQuery done. Of course your scenario may have additional or more complex requirements but this should serve as a basis to set it up.

Multilanguage AngularJS apps

Last two years, almost every project that I have worked on, has had the requirement of multilingual graphical user interface (GUI) and messages. This scenario may be important if your country has a multilingual environment or if you are opening to international markets and want to give your users the best possible user experience. The former is little easier as the number of supported languages is usually lower than the latter.

So, what is the problem definition here. We need to support dynamic language setting in GUI for two types of components:

  1. Labels
  2. Dropdown lists

In order to define the actual language the user is using, we chose to use a route parameter for it. Our route became something like this:

Route parameter :lang enabled us to get the user’s current language by calling

Then, we used angular library angular-translate which happened to be very convenient and easy to use for us. The setup is pretty easy. You include angular-translate.js file in your index.html and require reference to ‘pascalprecht.translate’ when defining your module, e.g.

After this, we create a json file for every language we wanted to define, eg. en.js file will contain the labels for English language (sq.js for Albanian, and so on), and it looks like this:

We also need to tell our app the translation configuration. I like to do this in a separate configuration file which I call translation.js (don’t forget to reference it in index.html) and it looks like this:

If later I want to add a translation for Albanian language, I will create one file sq.js which contain the translations e.g.

and I will add this line of code to the translation.js file

and the new language is automatically supported.

Now, in the controller that we want to use translation, we need to to tell the language to be used and we do it like by getting the param from route and pass it to $translate object:

In the view, we put the dynamic labels and messages by using an angularjs binding and filtering it with translate

Here we are, our labels will be translated automatically based on the route parameter :lang.

The labels are translated, now we need to translate the dropdown lists. To support list translation, as we already had a small number of languages to be supported, we chose to save list values in the database lookup tables in all languages, so basically, every lookup table has a structure similar to this:

id name_en name_sq

and when we return the json object for the lookup values, we return an object similar to the object below and bind it in our controller to a scope variable list

then our html select element will look like this

In this way, our ng-options will get automatically the language from lang parameter set in $scope from the $routeParams and it will automatically get the lookup name for the specific language

This might not be the best way to implement multilanguage angularjs apps but it worked pretty well in our case and in several other projects I have worked on.

Hope it helps to you as well.

Developing hybrid mobile apps with Phonegap, AngularJS, Bootstrap

In my post Develop mobile applications using web development skills, I pointed out a list of possible frameworks which can be used to create a hybrid mobile app. My favorite choice so far is using Cordova/Phonegap (Read my post on my opinion about Cordova/Phonegap) in combination with a hybrid app development framework. In my previous mobile applications I have developed, I used to use jQuery mobile as my framework of choice for developing the UI of my apps. Nowadays, I have switched to another combination, which is:

Cordova/Phonegap + AngularJS + Bootstrap

The hybrid mobile app architecture with Phonegap, AngularJS, Bootstrap looks like this:

The presentation layer is built with Bootstrap framework, the app domain is modelled using AngularJS, and the is packaged using Cordova/Phonegap to a native app. Let us go through the components of this hybrid mobile app architecture and describe them.

Bootstrap

Bootstrap is a mobile-first responsive front-end framework. What this mean? Bootstrap has an easy to use responsive grid which allows you to position your layout in a well structured responsive way. As the framework is built with mobile use in mind, it responds well to different screen sizes and adapts the layout of the app easily to different screen sizes. This is a good possibility to use the very same implementation for tablet and mobile devices of different screen sizes. And it is not only the grid that makes it special. It helps you manage typography, responsive images, forms, form validation messages, notification messages, responsive tables, and a good number of UI components. You can download it from getbootstrap.com.

AngularJS

AngularJS

AngularJS

A very powerful, full-featured JavaScript MVW framework. With AngularJS framework, you can give a structure to your app domain model and manage your app logic in a very flexible way. Everything is organized around a model which is displayed through a View. Views can be well structured templated HTML code styled and organized using Bootstrap. Controllers organize the communication between the View, Services, and all other parts. The framework supports a good routing mechanism, which can also be extended by other extension libraries for more powerful functionalities. There are a plethora of extension libraries for AngularJS which add value to the framework by filling in the gaps of the framework. You can get AngularJS from angularjs.org.

 

Cordova/Phonegap

Cordova is an Apache project which creates an underlying platform for developing multiplatform mobile applications. In our case, it makes possible the AngularJS+Bootstrap web app to be packaged to a native mobile app which can be published to the mobile markets and be instlalled in mobile devices. Adobe PhoneGap is a distribution of Cordova.

Basically what Cordova does is to make possible the web app to run inside a WebView component of a native app, we can say it as a native package of a web app. You can do the packaging using Cordova Command Line Interface (CLI) or using Adobe PhoneGap Build which does not require any installations.

The most powerful feature of Cordova in my opinion is the extension possibility by plugins. By installing specific plugins, you get access to device’s hardware such as camera, compass, geolocation, as well as other device specific APIs such as contacts, media, notifications, etc. Very powerful plugins such as barcode reading, push notifications, and many more, can give your application good features by writing few lines of code.

The development process

As we described the architecture parts, let us start with the process of developing hybrid mobile apps with Phonegap, AngularJS, Bootstrap. We start with creating a sample application  which shows you your current location coordinates and demonstrate the development process. The easiest way to start the app development is by creating initial template using Cordova/Phonegap CLI. We do this through this command (if you do not have cordova cli installed, here is the link showing how to do it: https://cordova.apache.org/docs/en/4.0.0/guide_cli_index.md.html)

The create command requires 3 arguments:

  1. The directory name to be created for generation of the project, in our case “blogSample”
  2. The second argument is the project identifier, in our case “com.ariancelina.blogSample”. Usually it is used as a reversed domain name identifier
  3. The third argument is the display title of the application, in our case “BlogSample”

In this sample code, I used phonegap to create the app. The command equally applies to cordova as well.

If you already had phonegap installed and the app was created successfully, inside blogSample directory you should have a config.xml file and four other directories (hooks, platforms, plugins, and www). Platforms folder contains builds for specific platforms, plugins directory contains installed plugins, and WWW directory contains all our web code (AngularJS + Bootstrap + other files).

To read our location coordinates we need to install the Geolocation plugin (Find the list of plugins) and we do that by executing this command:

Now that we have the initial structure, we need to add platforms to which we want to deploy, but to do that, we need to be inside out app directory, which in our case is blogSample. Adding ios platform is done using the command

After the platform is added, we can build our app using

We can repeat last two commands for all other supported platforms like android, windows phone, etc.

If we want to test our app, we can go to directory blogSample/platforms/ios and lunch BlogSample.xcodeproj and run the app in simulator or existing device.

We have our platform set up, now let us add the AngularJS and Bootstrap files. After we download these (download AngularJS as a zip file so you get all parts of it), we put inside blogSample/www/js directory AngularJS and Bootstrap js files: jquery-1.11.2.min.js (jquery is a dependency of bootstrap and can be downloaded from jquery.com)angular.min.js, angular-route.min.js and bootstrap.min.js. Inside blogSample/www/css directory we put bootstrap.min.css and bootstrap-theme.min.css files. And the last part here is to link these files in our main file index.html. We put css code in head section:

and near the closing body tag we link the javascript files

Now we have the setup ready and we can start coding the logic. We need three things to define to make it work, we need an angular route config which allows us to navigate from page to page, then we need an angular controller, and a view which will display the user his/her current location.

We start with the app.js file which contains the initialization of the js app. This file also is the place where the initialization events are placed. In our case, it looks like this:

We start by defining our angular app, blogSample (line 1). We initiate it and  define the modules which we need (ngRoute, ui.bootstrap). There are other interesting things happening here. As we are used to use jquery ready function to react when the page is loaded and ready for use, here we have onDeviceReady event which is fired when the app is loaded and we can start using it. Inside this event, we will get the current position of the device through this line of code

The getCurrentPosition function which gets the current latitude and longitude of the device, needs two functions as parameters, first being the function that is called if the current location can be obtained successfully, and the latter for errors. The error function is used to report the unavailability of the location. The success function is used to read the coordinates and bind them to our angular app, blogSample through this function

Now that we have our app setup ready, let us define two views, one about page and the other showing location information. Showing the coordinates inside the view is done using

AngularJS will substitute the values inside curly braces with current coordinates set in onSuccess function. But views do not access application level values. We usually link a controller with a view, and view is limited to the scope of that controller, so we need to define a controller to glue the coordinates to the view. The controller will look like:

and finally we add the router configuration to bind the controller to the view and enable the user moving between pages. The router has this code:

The router part defines one default url and ‘/about’ url. The default url ‘/’ binds to main.html view, and the ‘/about’ url binds to about.html view.

Now that we have all the building pieces in place, we need to add the reference of last created files in index.html and the references will look like this:

Now that everything is on place, we can deploy our app to the phone for testing, or run it in a simulator. Running the application is different depending on the platform. You may use the simulators that can be started from phonegap, by xcode, eclipse, or android studio, but for any serious app development, I would strongly suggest you try your app in a real device. I will not go into details about deployment as it is out of scope of this post, but in the simplest scenario, you may go to platforms folder inside  your phonegap project folder, and open the project of the specific platform and run the project from the respective ide.

The complete source code of this application can be found on GitHub https://github.com/acelina/phonegapWithAngularJs, you may download it and try it on your computer.

AngularJS at its simplest form

AngularJS is a very hot topic nowadays amongst web developers. It seems to be having a

AngularJS

AngularJS

momentum and as such getting high attention and interest. Being an extensible javascript framework and excellent framework for developing Single Page Applications (SPA), it is feature rich and evolving very fast.

As learning such a huge and fast growing framework could seem to be hard at the beginning, I will try to take a very simple form of it, and try to explain how can we create an AngularJS SPA at its simplest form. For the sake of demonstration, I will create a web page which displays basic contacts of famous web developers.

AngularJS is a Model-View-Controller framework, where Model serves the data, Controller takes the data from Model and delivers to View, and View displays the data. As we want to display some data, we need all three of the components. We have our contacts, which is our Model, then we need a Controller which will deliver the contacts’ list to the View, and we need a View to display the contacts’ list.

Before we start to create components, we need to define the Angular module which will form the base of our SPA, and it is done through this line of code:

var angularEg = angular.module('angularEg', []);

A new module is defined using angular.module. The first argument defines the name of the module, and the second argument specifies other required modules. We will leave it as an empty array as we have no dependency on other modules for this example. Although the second argument is optional, it has a significant meaning. If not specified, angular will look for an existing module with the name specified at the first argument, otherwise if specified a new module will be created.

Lets create now the components one by one.

Model

Our contact card will display contact’s name,  country, and his web page URL, so we need an object which will hold these data. Our model will look like this:


{
name: "Scott Hanselman",
country: "USA",
web: "http://www.hanselman.com"
}

This represents a single contact, and our Model will contain an array of such objects.

Controller

The controller in our case has only one duty, to make the data available to the view, so lets first define the controller using this code:

angularEg.controller('myContacts', function($scope){

});

The first argument to controller creation is the name of the controller, which in this case will be ‘myContacts’ and the second argument is the controller implementation. The $scope variable is the connection between the Controller and the View, and it is used to pass information from Controller to the View. The controller can get the data from model in various ways like loading data from a file, from an internal/external web service, etc. To keep it simple, I will hard code the data inside the controller.

angularEg.controller('myContacts', function($scope){

$scope.contacts = [{
name: "Arian Celina",
country: "Republic of Kosova",
web: "http://arian-celina.com"
}]
});

The controller is ready, lets continue with the view.

View

Our view will be a standard html page which displays the above specified information in div blocks. There are three things we need to do in view in order to bind the information from controller.

1. We need to specify that the view is for the angular module we have created and we do this by putting ng-app attribute in html tag

<html ng-app="angularEg">

2. We need to specify which part of this view is bound to which controller, and we do this by attaching ng-controller directive to the relevant container, in this case I will do it in body. This can be done in a granular level such as a specific div, or a global level such as body.

<body ng-controller="myContacts">

3. We need to display the contacts. There is a directive in AngularJS specifically to display collection of data such as arrays, and it is ng-repeat. I will repeat contacts and display them in this way:

<div class="w-row" ng-repeat="contact in contacts">

<div class="contact-brief">
<h2 class="contact-name">{{contact.name}}</h2>
<div class="contact-info">Country: {{contact.country}}</div>
<div class="contact-info">Web: {{contact.web}}</div>
</div>

</div>

The ng-repeat directive iterates through collection of contacts which he gets from the controller “myController” (remember, we defined variable contacts in $scope). A local variable contact is defined inside ng-repeat, this gives us the opportunity to access the object in iteration and access its properties and then the data binding is done by specifying the property and enclosing it with double brackets like {{contact.name}} (the handlebars syntax).

AngularJS will iterate over the array $scope.contacts and add the above specified div to the DOM for every element in the array.

The resulting app can be seen online on http://arian-celina.com/angularexample/index.html. Feel free to get the code from GitHub and play with it.

 

There is life beyond jQuery

I am a huge fan of jQuery library. For years, jQuery has been my ultimate tool for client side development, and I have used it in any web project I have undertaken. Few weeks ago, I took a project to develop a simple brochure style web site, which had to display a couple of static data, and I decided it to be a Single Page Application (SPA) for the sake of the simplicity and reuse of the page templates.

At the beginning, my idea was to do the dom manipulation with jQuery and templating using jsRender library, but during the planning phase, I thought I should take into consideration using a SPA framework or library. I did a little research on the web, consulted a friend of mine, and then shortened my list to DurandalJS and AngularJS. After giving a quick try to each of them, I decided to go with AngularJS.

Using HTML templates for pages and binding data to the templates was dead simple in AngularJS. The biggest implementation challenge on the project was the internationalization, as the site is multilingual in four different languages. With the help of Angular translate module I managed to translate the labels very easily, and by extracting the language using route params I made the app to decide on the language of controler. The app worked like a charm.

On overall, I managed to finish the whole project within three working days and the most interesting part for me was that I managed to do it without using jQuery at all. Ever since I have started to use jQuery, this is the first project that I have finished without using jQuery. I still think that jQuery is an amazing library and I will continue using it in the future, but there is one other thing, that certainly, I will start using more and more AngluarJS as well.