Using AngularJs to write single page apps

By Eugenia Pérez | 20 April, 2014

During these days I’m trying to learn a bit of AngularJs. Angular is a Javascript Framework which you can use to develop more responsive and usable apps. One of the key features of Angular is that makes simple developing what are called single page apps. Apart from MVVM binding, Angular has its own routing system. The result is that you can keep your presentation and data logic away one from the other, which makes application easier to maintain and scale.

In Angular it’s possible to query a rest API in a very straightforward way using ngResource. In the proof of concept I’m working on there is a Restful API written using Web API. Then ngResource only needs the URL to the API. And the basic methods the CRUD are wired up automatically.

In the following snippet you can see the initialization of the main module of the app, and a reference to a resource which uses ngResource:

var app = angular.module("runniac", ["ngRoute", "ngResource", "ngSanitize", "tableSort", "ui.bootstrap.datetimepicker"]);

app.factory("Event", ["$resource", function ($resource) {
    return $resource("/api/events/:action:id", { id: '@id', action: '@action' },
  {
    getExternal: { method: 'GET', isArray: true, params: { action: 'getExternal' } },
    importEvents: { method: 'POST', params: { action: 'import' } }
   });
}]);

Once this is done, this resource can be used for any other part in the app, for example, in the controller:

(function () {
"use strict";

   angular.module("runniac").controller("EventsCtrl", ["$scope", "$filter", "Event", "EventTypes",
   function ($scope, $filter, Event, EventTypes) {
       $scope.events = Event.query();
    }]);
})();

This is a small portion of what I’m doing right now but at the moment it looks promising and I have to say that Angular is a really enjoyable framework.

facebooktwittergoogle_plusredditpinterestlinkedinmailby feather

Leave a Reply

Your email address will not be published.