Tuesday 20 January 2015

Binding to input field through filters in AngularJS


  



1. Filtering with search pattern.

Filters are used to control the information bound to form elements or to say it binds data to the field.
In this lesson we will be creating a list of data and bind it to a search field to filter out the list based on the search criteria. Search field will be an input element, so when user type on the input the data will be filtered out to show only the list data matching the searched pattern. To bind the input element to the list the first thing we need to do is and one directive ng-model to the input field and the next thing to do is pipe (|) our ng-repeat directive value with the ng-model name given within the input field. So when we start typing in the input field our model will change correspondingly matching the value enter in the input field.

2. Filtering with sort by column.

    The next thing we are going to do is add one select element to create a combo list which will have the name of all the individual field used within the list and sort accordingly by a certain field. Say the data we fed into the page be [{'Name':'Sachin','Country':'India','Age':'40'}], so here fields are Name, Country and Age so we will feed Name, Country and Age into the combolist and when we will select any of the value then it will get sorted with that field.

3. Filter with orderby 

    Here we will add 2 radio buttons which will be labelled Sort by Ascending and Descending order. When we select the first radio it will be sorted in ascending order or else descending.

So here is the code given below showing all the 3 functionality.

<html ng-app>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
    </head>
    <body ng-init="myData=[
    {'Name':'Sachin Tendulkar','Country':'India','Age':'40'},
    {'Name':'Ricky Ponting','Country':'Australia','Age':'38'},
    {'Name':'Brian Lara','Country':'West Indies','Age':'39'},
    {'Name':'Jaque Kallis','Country':'South Africa','Age':'41'},
    {'Name':'Kumara Sangakara','Country':'Sri Lanka','Age':'37'}
    ]">
    <label>Search : </label> <input type="text" value="" ng-model="query" autofocus />
    <label>Order By</label>
    <select name="orderByKey" ng-model="orderByKey" >
        <option value="Name">Name</option>
        <option value="Country">Country</option>
        <option value="Age">Age</option>
    </select>
    <label>Order In</label>
        <input type="radio" ng-model="orderIn" name="orderIn" checked />
        <input type="radio" ng-model="orderIn" name="orderIn" value="reverse" />
        <ul>
            <li ng-repeat="data in myData | filter : query | orderBy : orderByKey : orderIn ">{{data.Name}} - {{data.Country}} - {{data.Age}}</li>
        </ul>
    </body>
</html>

No comments: