AngularJS Components for ASP.NET MVC Developers, Part 3: Angular Templating Fundamentals

It can be tough giving up server-side Razor templating. It’s strongly typed, looks familiar, and it just feels right. In this article I am going to show you how to take your knowledge of Razor templating and accomplish the same (and more!) on the client. Once you put in the time and get used to Angular’s way of doing things, I have a strong feeling you will never look back!

(Note: All directives covered in this article will be from Angular core. I will discuss custom directives in a future article.)
Full code example, follow along: Plunker

Model Binding (similar to @Model.* …but two way!)
In Angular, you bind to your JavaScript model using handlebar {{ }} notation.

Angular supports 2-way data-binding, meaning any change to the model in your view (using ngModel) will be persisted to your JavaScript model. This is most easily be demonstrated by the following code:

In this example the input tag is decorated with the ngModel directive, specifying “twoWayDataBinding” as it’s model. The ‘twoWayDataBinding’ template is placed below in the paragraph tag and will instantly be updated with any input from the above text-box. This works the same when the model exists in your controller and can be demonstrated through the use of the Batarang Chrome Developer Tool. This is perhaps the most powerful feature of Angular, no observerables or sacrifices are needed to wire up two-way data binding!

ngRepeat (similar to @foreach)
ngRepeat, in my opinion, is the king of all Angular directives. Similar to @foreach in Razor, you will use this in nearly every view in your application. The ngRepeat directive creates a template once for every item in the specified collection. This template is generally the child elements inside the parent element in which you specify ngRepeat but can also be used on a single item or more recently on a series of elements.

In this example, I am iterating over the elements in my ‘athletes’ collection, producing all items under my definition list tag for each element in my array. Also notice you can easily nest ngRepeat directives, as I am repeating over each sport for each athlete, producing the desired output.

ngShow – ngHide – ngIf (similar to @if())
As the names suggest, these directives let you toggle the display of elements on the page. ngShow will display an element if the value or expression provided is truthy and hide when falsey, where ngHide performs the opposite task. ngIf is similar to Razor’s @if() expression in that it completely removes the element from the DOM if the expression is falsey, and recreates when truthy. The syntax is as follows:

In the first example the ‘Hello World!’ alert box is displayed. When the user clicks the toggle button, the value of the ‘vm.helloWorld’ variable will be flipped to false displaying the ‘Goodbye World!’ alert box decorated with ngHide. The ngIf example evaluates whether to create the element based on the particular athletes rating. Unlike Razor templating, the display and existence of these elements will be re-evaluated as your underlying model changes. Please note, if you are hazy on truthy / falsey evaluations in JavaScript the quickest solution is to open your browser console and use the double exclamation expression.

ngClass (similar to @(Model.* ? “class” : “anotherClass” ))
Similar to ngShow and ngHide, ngClass will add or remove classes dynamically based on a truthy / falsey evaluation.

In this example the ‘bg-danger’ class is toggled by the below checkbox. Please note the single quotes around the ‘bg-danger’ class name, forgetting these is a common headache.

ng Filters (similar to string formatting (except filter…filter))
Filters in Angular allow you to quickly and easily format text, similar to what string formatting would accomplish in Razor views and C#.

By providing the single pipe character followed by the name of the filter you can manipulate the proceeding text into a format of your choosing. As an Angular developer you also have the power to write custom filters when core filters do not meet the requirements for your project.
Another popular use for filters is the filter ‘filter’ (that’s a lot of filters!). This filter allows you to quickly manipulate a collection based on user input.

In the example I am defining a filter of ‘textFilter’ in my ngRepeat directive. The ‘textFilter’ value is defined by user input into the filter input box. As the user types the collection below will be dynamically updated based on the defined criteria. Also be aware it is quite easy to add sort order to your collections by using the orderBy filter. Notice when defining orderBy filters the minus sign denotes descending order while the plus sign evaluates to ascending order when placed before the filter variable. Similar dynamic filtering and sorting would have likely involved a jQuery plug-in in the past.

Selects (generally accomplished in MVC with @Html.DropDownList() or Editor Templates)
Select lists in Angular applications can be created using the ngOptions directive.

As you can see, the ngOptions directive takes the value to display and the collection from which to draw these values. Angular also provides a solution for more advanced select lists where grouping is needed.

This syntax will group items in the select list by the described value, in this case the pet breed.
Putting it all together
The power of Angular templating is being able to put all of these (and many more + custom) directives together to create an extremely rich user experience. Below is an example, albeit contrived, of combining directives and filters in a table.

This simple example provides similar functionality to the table in the ngFilters section, while also allowing the dynamic update of ‘rating’ and the background of each table row based on the rating evaluation. This all can be accomplished explicitly with just a few lines of code.

I hope you now have a solid understanding of the fundamentals of Angular templating. For a complete list of core Angular directives (60+!) your best bet is to peruse the Angular API documentation. To get started writing custom directives I highly recommend Dan Wahlin’s series Creating Custom Angular Directives. Until next time, good luck and happy coding!

Next ArticleBreaking down AngularJS Unit Testing