Pages

Men

rh

10/24/2014

Learn AngularJS: Hour 3

Learn AngularJS: Hour 3

In hour 1 of this series we learnt to get started with AngularJS.
In hour 2 of this series we learnt about AngularJS Template.
In this hour we will learn about,
  • Filter
  • orderBy
  • Two way binding
image
Now filter can be applied to repeater directive by providing option filter. In filter we need to set value as
clip_image001
Let us consider understanding that what exactly happening here. First thing is Data Binding which is the core feature of AngularJS. Angular bind name of the input box to a variable in data model. This is the two way binding. Two way binding keeps input box and data model in sync.
image
Later we are using filter function. This function will use input box ng-model value to create new array that will contain filtered value based on matched ng-model value from input box. Next let us see that how easily orderBy function can be implemented in AngularJS. Let us say we have a drop down as below,
image
We have created a drop down with two options. Both options are having value as the properties of the controller. Next just to sort the order set orderBy function value to ng-model value of the drop down list.
image
For your reference full source code for Controller is given below,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var AuthorApp = angular.module('AuthorApp', []);
 
AuthorApp.controller('AuthorController', function ($scope) {
    $scope.authors =
        [
                { 'name': 'Dhananjay Kumar','age':'32' },
                { 'name': 'Pinal Dave', 'age': '35' },
                { 'name': 'Glen Block', 'age': '40' },
                { 'name': 'Dan Wahlin', 'age': '40' },
                { 'name': 'Mahesh Chand', 'age': '41' },
                { 'name': 'Prabhjot Singh', 'age': '42' },
                { 'name': 'Julie Learman', 'age': '38' }
        ];
 
     
});
Source code of View is given below,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html ng-app="AuthorApp">
<head>
    <title>Angular Demo</title>
    <script src="Scripts/angular.min.js"></script>
    <script src="Author.js"></script>
</head>
<body ng-controller="AuthorController">
 
    Search: <input ng-model="searchtext">
 
    Sort:
    <select ng-model="sortorder">
        <option value="name">Name</option>
        <option value="age">Age</option>
    </select>
 
    <ul>
        <li ng-repeat="author in authors |
            filter:searchtext |
            orderBy:sortorder">
            {{author.name}} is {{author.age}} years old
 
       </li>
    </ul>
</body>
</html>
I hope you find this hour 3 of AngularJS series helpful. Thanks for reading. Happy coding.

Source Collected from :http://debugmode.net/2014/08/08/learn-angularjs-hour-3/

No comments :

Post a Comment