Nowadays, it is commonplace for web apps to communicate with each other via APIs. For example, when you buy movie tickets online, the movie ticket web site uses a remote API to verify your credit card information is correct. In this tutorial I will examine how AngularJS can be used to make HTTP requests to a remote API and how to handle the API’s JSON response so that the view is updated.
Staying with the movie theme, I will demonstrate this by building a movie browser called Fastr, which will fetch a variety of different information about any movie you care to enter. In addition to AngularJS, Fastr will be built using Bootstrap for styling and Animate.css for some snazzy effects.
This is what we’ll end up with:
The code for this project is available from our GitHub repo, or you can view a working demo on CodePen.
The Project Structure
We will be keeping the code in a modular structure as follows:
[code language="bash"] css/ animate.min.css bootstrap.min.css style.css js/ angular.min.js app.js partials/ main-info.html related-results.html index.html [/code]The file index.html will contain the main view for our app. The majority of it is boilerplate, but let’s examine where the action takes place:
[code language="html"] [/code]As you can see, we have used ng-model to bind the input field (where the users will enter the movie name) to the search model (which we will declare in our controller). We have also used the ng-change directive to ensure that every time the input changes a change function will be called in our controller. This function will be responsible for initiating contact with the remote API.
The main-info and related-results divs will be used to display information about the current movie and a list of related movies respectively. The information will be displayed in partials which are fetched, compiled and included by the ng-include directive.
Continue reading %Making API Calls in AngularJS using Angular’s $http service%
by Tanay Pant via SitePoint
No comments:
Post a Comment