Working with AngularJS Views and Directives - (Project Tracking Website Part IV)

Posted by: Pravinkumar Dabade , on 3/28/2015, in Category AngularJS
Views: 26829
Abstract: Use some of the built-in AngularJS Directives and learn how to apply filters, to sort and filter a table.

Directives in AngularJS play an important role. Directives can be used to teach new tricks to HTML, and you can even create your own HTML tags or attributes. Directives also help in keeping the mark-up more fluent  and defines a nice way of separating code and mark-up from each other.

View is a HTML template. View is nothing but the information you want to render to the end user’s browser. A view in AngularJS is also called as compiled DOM. View makes use of directives to render the data with HTML template.

This article is Part IV of the Project Tracking Website built in AngularJS and ASP.NET Web API. So far, we have introduced AngularJS, created a REST based service using ASP.NET Web API, and have dived into AngularJS Controllers.

Thanks to Ravi Kiran to review this Angular series and fix the bugs.

We have already seen the $scope object which provides a Model to the View. Model code is not intermixed with the HTML code we write into our views. Rather data is moved from the model to views by using data binding expressions. This way developers can achieve Separation of Concerns (SoC). Since Models are independent of Views, they can be bound to any View. This binding of model is done with the help of AngularJS Directives.


We have already seen some Angular directives in our previous articles like ng-app which bootstraps AngularJS, as well as ng-controller that makes the controller available to HTML. From the controller, we can bind the data to the views using Angular {{expression}}.

In this article, we will look at a couple of additional AngularJS directives which come out-of-the-box with Angular. One of them is ng-repeat. Let’s try using ng-repeat directive into our EmployeeDetails.html page that can be found in the source code accompanying this article. Modify the service URL in our EmployeesController.js file. The service URL is as follows:


Now we will modify the EmployeeDetails.html page as shown in following code –

    <tr class="success" ng-repeat="emp in Employees">

Replace the <tbody> of EmployeeDetails.html page with above code. The output of the above code is shown here:


In this code, we have used the ng-repeat directive of AngularJS. It is similar to the for or foreach loop in .NET. Here we are getting an IEnumerable<Employee> collection using ASP.NET Web API. We are using this collection as a model in our Angular Controller. Using this model, we are iterating the objects of employees, into our view. This is a very helpful directive which repeats through the objects in the collection to display the data on the view.

Now let’s try adding a filter to search a particular Employee from the collection and display the employee based on given Employee Name or Employee Name character. Till now, we have fetched the model and used it in our Views. It also works the other way. We can make our views talk back to our models which are there in our controllers.

To add a search filter based on Employee Name, we will modify the EmployeeDetails.html page by adding HTML input elements as shown below –

<form name="searchEmployeeForm" ng-submit="SearchEmployee(EmployeeName)">
    Enter Employee Name Or Character To Search - <input type="text" required placeholder="Enter EmployeeID" ng-model="EmployeeName" />
    <input type="submit" value="Search Employee" />

Add the above code just after the <H1> tag. In the above code, we are using ng-model directive which enables us to send the data back to the model. Based on this data, we will make a search for an employee using EmployeeName property. Make sure that EmployeeName property is declared in our model, which we will do in the following steps. Also notice that we are using ng-submit directive which will give a call to SearchEmployee function from our controller.

Now let’s modify the EmployeesController.js file so that we can search the employee based on EmployeeName property as a searching criteria. The code is shown below –

(function () {
var EmployeesController = function ($scope,$http) {
var employees = function (serviceResp) {
            $scope.Employees =;

        $scope.SearchEmployees = function (EmployeeName) {
            $http.get("http://localhost:2464/api/ptemployees/" + EmployeeName)
            .then(employees, errorDetails);
var errorDetails = function (serviceResp) {
            $scope.Error="Something went wrong ??";
        $scope.Title = "Employee Details Page";
        $scope.EmployeeName = null;
    app.controller("EmployeesController", EmployeesController);

In the above code, we have added the SearchEmployee() method to our $scope object as a model. This method will search for Employees based on employee name or the character of an employee name. We have also declared EmployeeName property in our controller at the end of this code. The SearchEmployees method fetches the Web API method. I have modified the method GET as shown here:

public HttpResponseMessage Get(string name)
    var employees = EmployeesRepository.SearchEmployeesByName(name);
    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, employees);
    return response;

The Employee Repository code is as shown here:

public static List<Employee> SearchEmployeesByName(string employeeName)
    ProjectTrackingDBEntities dataContext = new ProjectTrackingDBEntities();
    var query = from employee in dataContext.Employees
    where employee.EmployeeName.Contains(employeeName)
    select employee;
    return query.ToList();

After all these changes, now run the EmployeeDetails.html page and see the output.


In the above output, we are searching for employees whose name contains the ‘J’ character in it.

AngularJS Filters extend the behavior of binding expressions or directives. Filters are used with binding expressions to format the data being bound. When they are used with directives, they add some additional actions to the directives. Out-of-the-box, AngularJS provides a number of filters which we can use to format the values of an expression and display the values/data into our views. You can make use of filters in Views, Controllers and Services. The syntax of using filters into views is {{ expression | filter1 | filter2 | ...}}.

We will now try a filter which will sort the data using employee name. To sort the data, let’s add a filter in our ng-repeat using a | [pipe] operator as shown here:

<tr class="success" ng-repeat="emp in Employees | orderBy:'employeeName'">

In the above code, we are adding filter in our ng-repeat directive. The orderBy:’employeeName’ will sort the data using Employee name in an ascending order. You can observe the output here:


To display the data in descending order, you can change the filter as shown here:

<tr class="success" ng-repeat="emp in Employees | orderBy:'+employeeName'">

In the above code, to sort the employee names in descending order, we have used (-) minus sign. Likewise, you can make use of (+) sign to sort it in ascending.

You can also make use limitTo filter to limit the number of records. For example, let us say at a time you want to display 5 employees. To display the restricted number of records in our EmployeeDetails.html page, let’s modify the ng-repeat directive as shown here–

<tr class="success" ng-repeat="emp in Employees | limitTo:5 | orderBy:'-employeeName'">

The output is shown here:


Figure – 4

Now if you run the ProjectDetails.html page, the date is getting displayed with time. You can apply the date filter as shown in following code –

<tr class="success" ng-repeat="proj in Projects">

The output of this page is as follows: 


You can make use of different date formats like – fulldate, longdate, mediumdate, shortdate etc. Now let’s open EmployeeDetails.html page and run it. I am using the ‘Z’ character to display employees whose employee name contains Z. 


If you observe, the output displays an Employee table heading without data. We can make the heading invisible using the ng-show directive when the filter doesn’t produce any result. Apply ng-show directive in our table tag as shown in the below code and try running the application with Z character. Now you will not see the table columns when Employees model is null. The ng-show attribute will evaluate the Employees model and accordingly it will either display the table or hide the table.

<table class="table table-striped table-hover" ng-show="Employees">

Likewise, there are a number of directives which you can use in AngularJS. You can also design a Custom Directive which we will see later in this series. Apply the search on various views as per your requirement in our views. In our next article, we will take a look at how Services play an important role in AngularJS.

Summary – In this article, we saw how to use some of the built-in AngularJS Directives and how to apply filters, to sort and filter a table. In the next article, we will see how to use AngularJS services. We will create AngularJS services to implement the logic of our Project Tracking website. Stay tuned!

Download the entire source code of this article (Github)

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Pravinkumar, works as a freelance trainer and consultant on Microsoft Technologies. He is having over 10 years of experience in IT and is also a Microsoft Certified Trainer(MCT). He has conducted various corporate trainings on all versions of .NET Technologies including .NET, SharePoint Server, Microsoft SQL Server, Silverlight, ASP.NET, Microsoft PerformancePoint Server 2007 (Monitoring). He is passionate about learning new technologies from Microsoft. You can contact Pravinkumar at dabade[dot]pravinkumar [attherate] gmail[dot]com

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Alex Y on Tuesday, March 31, 2015 1:18 PM
Very much appreciated for your help in understanding this topic.
Comment posted by Alex Y on Wednesday, April 1, 2015 8:51 AM
Very much appreciated for your help in understanding this topic.
Comment posted by Alex Y on Thursday, April 2, 2015 9:39 AM
Very much appreciated for your help in understanding this topic.
Comment posted by Alex Y on Friday, April 3, 2015 8:26 AM
Very much appreciated for your help in understanding this topic.