Sunday, April 24, 2016

AngularJS in Play

Motivated by countless number of books that I own that are published by Manning Publications and follow in Action series, I would like to post a very simple AngularJs application that you can use to query iTunes for your favorite song, artist, or album. Let's get started.

Let's create HTML file that would hold our interface and call it iTunesSearch.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
</html>
 
In the same folder, create js folder and download angularjs file.
 
Finally add bootstrap to make our work a little prettier. 
 
Now let's add these files into our html (see my previous post of proper placement of js files)

Now to make html understand angular add ng-app to the html tag and name it: iTunesSearchApp.

Our code should look like:

<!DOCTYPE html>
<html lang="en" ng-app="iTunesSearchApp">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <link rel="stylesheet" href="bootstrap/css/bootstrap.css">
</head>
<body>

    <script src="js/angular.min.js " type="text/javascript "> </script>
    <script src="js/underscore-min.js " type="text/javascript "> </script>
</body>
</html>
 
Now it is time to add iTunesSearchCtrl js that would hold business logic of our application, i.e. business of 
querying iTunes for data!
 
It can be as simple as 
 
var iTunesSearchApp = angular.module('iTunesSearchApp', []);
 
to get started and don't forget it add it to your main html file!
 
Let's add a search field where user would be able to add some text and a button that would execute
the search.
 
Add following to the html
 
<div ng-controller="iTunesSearchCtrl">
    <input type="text" ng-model="searchTerm">
    <button class="btn" ng-click="searchItunes()">
        <i class="glyphicon glyphicon-search"></i> Search
    </button>
</div>
 
Here we add a div that will be controlled by iTunesSearchCtrl with searchTearm input field being our
search query term and searchItunes() function executing search query against iTunes Rest API.
Not glyphicon-search here... now you get a cool looking search image for free that's to bootstrap.

Inside of iTunesSearchCtrl add:

<!-- Controller: iTunesSearchCtrl -->iTunesSearchApp.controller('iTunesSearchCtrl', function($scope) {
    $scope.searchItunes=function() {
        console.log("Searching for " + $scope.searchTerm);
    };
});
 
This would attach iTunesSearchCtrl to the iTunesSearchApp in which it would define function searchItunes
that will be able to get bound variable searchTerm within the scope and be able to display it in console log.
Go ahead and try to fire your html up and see console log adding Searching for ... once you hit Search button.

Well, it is not that interesting... let's query actual iTunes API available at:

http://itunes.apple.com/search?term=
 
First of all, you need to make sure that now you can call REST API - something that is very easily done
via taking advantage of angular-resource.js file which should be downloaded and included in your html file.
As well as declaring it in your controller.

var iTunesSearchApp = angular.module('iTunesSearchApp', ['ngResource']);
 
Here we say that we want angularjs to know about resource directive.
 
and now our controller should look like this

var iTunesSearchApp = angular.module('iTunesSearchApp', ['ngResource']);

<!-- Controller: iTunesSearchCtrl -->iTunesSearchApp.controller('iTunesSearchCtrl', function($scope, $resource) {
    //http://itunes.apple.com/search?term=<search term>    $scope.itunes = $resource('http://itunes.apple.com/:action',
                            {action:'search', term:'', callback:'JSON_CALLBACK'},
                            {get:{method:'JSONP'}});

    $scope.searchItunes=function() {
        console.log("Searching for " + $scope.searchTerm);
        $scope.itResult = $scope.itunes.get({term:$scope.searchTerm});
    };
});
 
As you can see searchItunes function is now calling itunes resource that is defined above and contain such
information as restful endpoint ('http://itunes.apple.com/:action), type of action (action:'search'), 
default search term (term:''), callback method (callback:'JSON_CALLBACK') and a little magic
for Xsite scripting ({get:{method:'JSONP'}}).
The result will be stored in itResult and shall be displayed on our main html page. Here is the code for it:

<table class="table table-bordered">
    <tr>
        <th></th>
        <th>Album</th>
        <th>Song</th>
        <th>Price</th>
    </tr>
    <tr ng-repeat="song in itResult.results">
        <td><img src={{song.artworkUrl30}}></td>
        <td>{{song.collectionName}}</td>
        <td><a href={{song.trackViewUrl}}>{{song.trackName}}</a></td>
        <td>{{song.trackPrice}}</td>
    </tr>
</table>

Here we iterate thru itResult.results and for each song we display art work url and other information.
Feel free to examine returned JSON object and pull whatever you need. 

Now, let's add some code to make this table available only when Search button is clicked and also let's
make it clear out our search.

Add Clear button to html page

<button class="btn" ng-click="clear()">
    <i class="glyphicon glyphicon-refresh"></i> Clear
</button>
 
and add ng-show directive to your table that will be initialized via itunes.show bind variable that is set
to false when page loads for the first time.
 
Add following to iTunesSearchCtrl
 
$scope.clear=function() {
    console.log("Clearing...");
    $scope.searchTerm='';
    $scope.itunes.show = false;
};

$scope.itunes.show = false;
 
and test out the application!

That's it... it was quick and fast hand on tutorial and assumed some of the knowledge of AngularJS. 
Complete code is available at: https://github.com/krinkere/iTunesSearchApp

 


 
 


No comments:

Post a Comment