Sitecore with Angular JS Part 1

I wanted to provide a simple example for anyone to get started with incorporating AngularJS into a Sitecore implementation. This article will go over creating:

a service class for retriving albums from Sitecore

an API Controller

Domain Transfer Object

a very simple AngularJS module for listing albums

For this example, we are building a music store. The store needs to display albums and this page will have filtering such as display albums whose release date is between two dates. The next post will cover more on filtering, but for this example, we will start some implementation.

Let's start by building the AlbumService class. Also, this assumes you are using Glass Mapper for interacting with Sitecore items and search index.

Album Service Class

Albums will be retrived from a Sitecore index. We will build a method GetReleasedAlbumsBetweenDates that will query the index for items as the index will hold the release date field from the Sitecore item for Album.

AngularJS

To start building out the client side, we need to build the Album module. As mentioned before, AngulurJS has a concept of modules so we want to encapulate any logic that will be used for managing albums.

Here we place the listing of albums in a partial view and for the sake of simplicty we have added the initialization of the app and the controller here. If AngularJS was going to be used throughout the site, we will probably put a little bit more planning on how AngularJS is introduced in an ASP.NET MVC site under Sitecore.

We can see a mocked version of this on JSFiddle:

In further posting, we can start to tackle other aspects of AngularJS and how that might change what we put together so far.

One of the biggest struggles I faced with using AngularJS was how to structure and provide good separation. So far we have:

As more modules are created and dependencies need to be managed, the js folder will become complex. For example, you notice that I declare the module for albums and the app in js/app/albums/albums.js. Much of this should be moved to a new file js/app/app.module.js. As more modules are created, this file will be a good place to manage them and how they are dependent on each other.

One resource that was very helpful was John Papa's styleguide on AngularJS. I constantly referenced this document in order to have some good practices and consistency with AngularJS.

We have not built out how the filter form is wired up and how that interacts with the albums module.

The next post we can cover working with filtering the results with the start and end dates and adding on additional concepts in AngularJS such as: