Tags

, , , ,

Disclaimer : This blog post is case sensitive.

Angular is replacing hard coded Ajax these days and its been a very good option as a jQuary alternatively. Honestly Angular and jQuery are two different things, Angular is a framework whole jQuery functions as a library, they have separate functionalities but most people who were depending on jQuery for everything is now coming to Angular because of some good builtin things in Angular such as templating, data binding and routing capabilities in single page apps.

I am not an Angular fanatic, but trying and experimenting something so I can learn the things. In this blog I am going to discuss about a Google Instant search like implementation in Angular

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<p>Name: <input type="text" ng-model="name.Name"></p>
<ul>
  <li ng-repeat="x in names | filter:name">
    <p ng-bind-template="{{x.Country }}"></p>
  </li>
</ul>

</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
    $http.get("http://www.w3schools.com/angular/customers.php")
    .success(function (response) {$scope.names = response.records;});
});
</script>
</body>
</html>

This is a very simple HTML code I got from W3Schools and added some modifications. What this does is… TRY IT 🙂

Lets have a look at the code. Here I have a controller customersCtrl for the app myApp. The functionality of the controller is to fetch results from the URL http://www.w3schools.com/angular/customers.php go to the page and see how its formatted. This is how Angular fetch and decode JSON. The method we are using is $http.get. In case you are wondering what is an $http. Angular has a good documentation for it. On success callback on $http.get the controller created an application object property names. Remember $scope is the application object and $scope.names is its property which stores names which contains the records from the response we get from the $http.get call.

Now lets move to the DOM manipulation, typically we call it a View. There what happens is, we put a repeater with ng-repeat which repeats the items from names this is the same property that was previosuly $scope.names and its filtered with ng-model which is name which gets the Name from the response. Finally it will list Country which have the Name.

Try this code and try to implement your own, so you will get a very clear picture.

Advertisements