OdeToCode IC Logo

Starting with AngularJS

Monday, February 18, 2013

In my MVC 4 Fundamentals video I have a section using the ASP.NET Web API on the server with jQuery and Handlebars on the client to build a somewhat interactive UI. A few people have asked what the code would look like with AngularJS.

The first part of the example, display a list of videos, is easy with Angular. Here is the HTML:

<div ng-app ng-controller="VideoController">    
        <tr data-id="{{video.Id}}" ng-repeat="video in videos">
                <button class="editVideo">Edit</button>
                <button class="deleteVideo">Delete</button>

The ng-app directive represents the application "root" for angular. Most applications would have ng-app on the body element, or the top html element, but you can also root the application further into the DOM. The ng-controller directive provides the name of a controller function for Angular to find and invoke. The controller provides the model and allows us to use data binding in between the model and the view (the HTML).

The controller function looks like this:

var VideoController = function($scope,$http) {
    $http.get('/api/videos/').success(function(data) {
        $scope.videos = data;

Angular will inject the $scope and $http parameters into the controller (names are significant). $scope is where we can place the model, while $http is a service that provides low-level HTTP communication (we'll see a higher level service in a later post). The above code is calling a Web API controller on the server to retrieve a list of videos, and placing them into the $scope when the call is successful. Back in the HTML, an ng-repeater will loop through the videos when they become available (Angular knows when the model changes), and outputs table rows with video information (via {{ }} templates).

The above is a quick demonstration of why I like Angular. It's quick, clean, and easy to learn. In my original demo I also inserted, deleted, and edited videos. We'll take a look at these scenarios next.