AngularJS - Creating a User Directory

The goal of this tutorial is illustrate the basic components of AngularJS by creating a simple user directory. Most of the code here follows John Papa's Angular Style Guide. If you are just getting started with Angular this should be your next stop after reading through the official docs. John provides a great set of best practices that will help you create clean, maintainable projects.

The code for this tutorial can be found here. (Note: if you download these files make sure to remove the pre-numbering (1-, 2-, etc.) on the files names. Those numbers are there to make the files show up in the right order in the Github Gist).

The first step is creating the index.html file. You can see a mostly normal looking html file except for 2 things:

  • ng-app="directoryApp" - this declaration tells Angular that you want to do some Angular stuff somewhere inside this file
  • ng-view="" - this is used to tell Angular where we want our views injected (similar to @RenderBody in ASP.NET MVC)

The next step is to create the app.js file. Angular recommends using the MVC pattern, and that is what we are using here. The code comments will explain most of what is going on but here are the main components at work:

  • ngRoute & $routeProvider - this is the router which works a lot like the router in ASP.NET MVC. For each URL you define a controller and template to inject into the page.
  • dataService($http, $q) - this is the factory (or service) used to expose the API endpoints to the controller.
  • DirectoryController($scope, $http, $filter, dataService) - this is the controller that will be used for the main route.
  • vm.users = []; - this is the model that will be bound to the view.

The final step is to create the view (directory.html). Here are the important pieces of the view:

  • ng-controller="DirectoryController" - this directive tells Angular which controller to use for this view.
  • ng-repeat="user in vm.users |" - this is just a for loop that iterates through the data model and renders the view accordindly (the razor equivalent would be something like: @foreach (var user in vm.users){} ).
  • {{}} - this is the handlebars style syntax Angular uses for data binding.

For more complex apps you will likely want to have an organized file structure and separate out all of the modules into separate files. But the intention of this exercise was to keep things as simple as possible so you should be able to put these three files in a directory and run your app. I'm using JSONPlaceholder to provide the dummy data and hopefully it will still be around when you come across this tutorial. I hope you enjoyed learning a little about AngularJS.

The Code

The Final Product


comments powered by Disqus