Binding data with angular js and applying client side search filter

AngularJS introduction

AngularJS use HTML5 directives. AngularJS is written in javascript just like jquery. you need to add reference of AngularJS library in your application and then you can manipulate HTML5 tags. You can use AngularJS on JSON objects, sending GET and POST calls to server, and client side validation. AngularJS use MVC architecture so you can define controller, Model and view in AngularJS.

objectives

In this article we will learn how we can call Asp.net MVC controller using AngularJS and bind json response with HTML5 controls. After that we apply search filter on our data. Remember that this search is done by AngularJS on client side. no server side call occur.

GET Started

Create a new asp.net mvc project and Add a new controller name it AngularJSController. Add a index Action result and json Action methods.

AngularJSController Code

public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public JsonResult CountriesList()
        {
            pubsEntities dbcontext = new pubsEntities();
            dbcontext.Configuration.ProxyCreationEnabled = false;
            return Json(dbcontext.authors.ToList(), JsonRequestBehavior.AllowGet);
        }

i use Database first Entity framework approach to connect with pubs database. please Read this article for more details.

Now we create our view which call our json ActionResult and show authors first name and last name and apply search filter. Right click on index ActionResult and click on Add view.

View Code

@{
    ViewBag.Title = "Index";
    Layout=null;
}
<html ng-app="authorApp">
<head>
    <meta charset="utf-8">
    <title>Angular.js Example</title>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
    <script>
        var authorApp = angular.module('authorApp', []);
        authorApp.controller('authorslist', ['$scope', '$http', function (scope, http) {
            http.get('/AngularJS/CountriesList').success(function (data) {
                scope.authors = data;
            });
        }]);
    </script>
</head>
<body ng-controller="authorslist">
    Search:<input ng-model="query" type="text" />
    <table>
        <tr>
            <th>Country</th>
            <th>Population</th>
        </tr>
        <tr ng-repeat="author in authors | filter:query">
            <td>{{author.au_lname}}</td>
            <td>{{author.au_fname}}</td>
        </tr>
    </table>
</body>
</html>

First we define ng-app directive with authorApp then create a variable type of pre define ng-app and call its controller which define in belwo body tag. using http.get method we send a get request to server and fetch authors list and in body we use ng-repeat for a loop to show all results. filter:query used to search in authors list when ever you put a word, charter or a string it will bring all the matching records.