Aside from ability to extend HTML easily AngularJS also offers a simple way to interact with external APIs. In this tutorial, I will show you how to use Services to access GitHub's API and create a simple repository browser.
Let's start with this basic HTML template:
<!DOCTYPE html> <html> <head> <title>GitHub Search</title> </head> <body> </body> </html>
Now add the AngularJS script in the <head>
of the document:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
After that you can add this CSS style inline or in separate a file:
* { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; font-family: sans-serif; } body, html { margin: 0; } p { margin: 0; } input { width: 100%; } pre { white-space: pre-wrap; white-space: -moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; word-wrap: break-word; } div.repo { border-bottom: 1px solid; cursor: pointer; } #search, #repo, #user { float: left; } #search { width: 20%; } #repo { width: 60%; } #user { width: 20%; }
It's nothing fancy as you can see, only a basic layout that puts the search box on the right, repository information in the middle, and user's repositories on the right. We also have to wrap the lines in the <pre>
tag that we will use to display the README file contents, since they are usually in GitHub Flavored Markdown and some lines would overlap with the user's repository list.
Of course, you can add more style to make it more pleasing to the eye, just keep in mind that the screenshots in this tutorial will show the basic look.
You can put the JavaScript code that we will write later either inline in the <head>
of the document, or in a separate file, but it has to be under the AngularJS script.
Now we can create a module for our app:
var app = angular.module('githubsearch', []);
Let's add it to the <body>
tag using the ngApp
directive:
<body ng-app="githubsearch">
We will also need a controller for our app. To keep it simple, it will be only one for the entire app, so we don't need to deal with passing information between controllers:
app.controller('SearchController', function SearchController($scope) { });
Let's define our GitHub
service:
app.factory('GitHub', function GitHub($http) { return { }; });
We are using the app.factory()
method so we can just return the object with some methods to use later. We will be using the $http
service to get data from GitHub's API.
The first method in our service will search for repositories using GitHub's API. The usage of the $http
service is pretty simple (this function goes into the object returned by our factory function):
searchRepos: function searchRepos(query, callback) { $http.get('https://api.github.com/search/repositories', { params: { q: query } }) .success(function (data) { callback(null, data); }) .error(function (e) { callback(e); }); }
The $http.get()
method is a shorthand for doing GET
requests. The first parameter is the URL that we want to access. The second one is a object with options. We only need the params
object here - it's a hash of query parameters that will be added to the request (the q
parameter is a search string, as described here).
$http.get()
returns a promise. We can attach success()
and error()
listeners to it and call the callback function accordingly.
To make use of the function that we defined in the previous step we will have to add a search box to our HTML. The code is pretty simple:
<div id="search"> <input ng-model="query" placeholder="search" ng-keyup="$event.keyCode == 13 && executeSearch()"> <div class="repo" ng-repeat="repo in repos" ng-click="openRepo(repo.full_name)"> <strong>{{ repo.full_name }}</strong> <p>{{ repo.description }}</p> </div> </div>
We use ngModel
directive to bind the value of this input field to the query
variable in the scope and ngKeyup
to call the executeSearch()
function when user presses the enter key (hence the $event.keyCode == 13
comparison). We can't use conditional statements in AngularJS expressions, but a simple logic operation (AND) will do fine.
Under the input field, we use ngRepeat
to display the search results. We will display the repository's full name and description (you can see all of the fields available in this example in the GitHub's API documentation if you want to display something different).
We also use ngClick
to call the openRepo()
function with the repository's full name so we can display information about it. We will define this function later.
Now we can finally make use of the service we created. First, add the GitHub
parameter to the controller function (so the service can be injected by AngularJS):
app.controller('SearchController', function SearchController($scope) {
Now define the executeSearch()
function:
$scope.executeSearch = function executeSearch() { GitHub.searchRepos($scope.query, function (error, data) { if (!error) { $scope.repos = data.items; } }); }
As you can see, we call the GitHub.searchRepos()
method with the search string from $scope.query
and in the callback we put the search results (from data.items
) in the $scope.repos
variable.
That is all you need to do to display the search results. Open the HTML file in your browser and try searching:
Now that we have the search functionality we can display some information about the repository the user selected. Let's create a function to get the repository's data in our service:
getRepo: function getRepo(name, callback) { $http.get('https://api.github.com/repos/'+ name) .success(function (data) { callback(null, data); }) .error(function (e) { callback(e); }); }
The name passed to this function must be a full name (author's name, slash, repository's name - like angular/angular.js
) since we have to pass it to the GitHub API (like shown here).
The contents of the README file are not inside the data we retrieved from the previous function. Instead, there is another API call to get it, so we have to create another function:
getReadme: function getReadme(name, callback) { $http.get('https://api.github.com/repos/'+ name +'/readme') .success(function (data) { callback(null, atob(data.content)); }) .error(function (e) { callback(e); }); }
This one is pretty much the same as the two previous ones, only the url changes. We are also using the atob()
function to decode contents of the README file, since it's base64 encoded. Getting contents of the README file is described here in the GitHub's API documentation.
The reason that we did not chain the two requests in one function is that some repositories don't have any README file. If we were to continue like that, the application would fail.
We will display repository's full name, number of people watching it and the README file in another <div>
element:
<div id="repo" ng-show="activeRepo"> <strong>{{ activeRepo.full_name }}</strong> <em>Watched by {{ activeRepo.watchers_count }} people.</em> <pre>{{ activeRepo.readme }}</pre> </div>
We will store that information in the activeRepo
variable in the scope of the controller. There is also the ngShow
which will show the element only if there is any data to be displayed (otherwise you would see a "Watched by people" text there with no repository selected).
We also have to update our controller so it gets the repository data and puts it in the scope. Create the openRepo()
function that we attached to the ngClick
directive earlier:
$scope.openRepo = function openRepo(name) { GitHub.getRepo(name, function (error, data) { if (!error) { $scope.activeRepo = data; GitHub.getReadme(name, function (error, data) { if (!error) { $scope.activeRepo.readme = data; } else { $scope.activeRepo.readme = 'No README found!'; } }); } }); }
As you can see we first use the GitHub.getRepo()
method, check for errors and then place the data in the activeRepo
variable. After that we get the README file and in case it does not exist we inform the user about that fact.
Now you can run your app again and see how it
To add some functionality to our app we will display all repositories of the selected repository's owner on the right side of the screen. This will require another method in our service:
getUserRepos: function getUser(name, callback) { $http.get('https://api.github.com/users/'+ name +'/repos') .success(function (data) { callback(null, data); }) .error(function (e) { callback(e); }); }
Which looks pretty much the same like the other ones (and you can read more about this API request here).
This is basically a copy of the HTML for the search box, but we display user's name instead of the input field and the repository list is in the user
object instead of the scope itself:
<div id="user"> <strong>{{ user.login }}</strong> <div class="repo" ng-repeat="repo in user.repos" ng-click="openRepo(repo.full_name)"> <strong>{{ repo.name }}</strong> <p>{{ repo.description }}</p> </div> </div>
At this point, you should have a working AngularJS application that retrieves GitHub repositories based on a search string. You can continue to iterate on this by adding more features, or giving it a different presentation through styles.
Whatever the case, all questions, comments, and feedback is welcome!
New Course: Practical React Fundamentals
/20 WordPress Video Plugins and Players to Add Engagement
/Preview Our New Course on Angular Material
/Build Your Own CAPTCHA and Contact Form in PHP
/Object-Oriented PHP With Classes and Objects
/Best Practices for ARIA Implementation
/Accessible Apps: Barriers to Access and Getting Started With Accessibility
Dramatically Speed Up Your React Front-End App Using Lazy Loading
/15 Best Modern JavaScript Admin Templates for React, Angular, and Vue.js
/15 Best Modern JavaScript Admin Templates for React, Angular and Vue.js
/10 Best WordPress Facebook Widgets
13Hands-on With ARIA: Accessibility for eCommerce
/New eBooks Available for Subscribers
/Hands-on With ARIA: Homepage Elements and Standard Navigation
/20 Best WordPress Calendar Plugins and Widgets
/How Secure Are Your JavaScript Open-Source Dependencies?
/New Course: Secure Your WordPress Site With SSL
/Testing Components in React Using Jest: The Basics
/15 Best PHP Event Calendar and Booking Scripts
/Set Up Routing in PHP Applications Using the Symfony Routing Component
1 /How to Build Complex, Large-Scale Vue.js Apps With Vuex
1 /Creating Stylish and Responsive Progress Bars Using ProgressBar.js
/Set Up an OAuth2 Server Using Passport in Laravel
/Getting Started With Redux: Connecting Redux With React
/Getting Started With Redux: Learn by Example
/Introduction to API Calls With React and Axios
/Introduction to Popmotion: Custom Animation Scrubber
/Introduction to Popmotion: Pointers and Physics
/New Course: Connect to a Database With Laravel’s Eloquent ORM
/How to Make a Real-Time Sports Application Using Node.js
/How Laravel Broadcasting Works
/Getting Started With Redux: Why Redux?
/Building the DOM faster: speculative parsing, async, defer and preload
1 /20 Useful PHP Scripts Available on CodeCanyon
3 /Single-Page React Applications With the React-Router and React-Transition-Group Modules
/12 Best Contact Form PHP Scripts
1 /Getting Started With the Mojs Animation Library: The ShapeSwirl and Stagger Modules
/Getting Started With the Mojs Animation Library: The Shape Module
Getting Started With the Mojs Animation Library: The HTML Module
/Project Management Considerations for Your WordPress Project
/Introduction to the CSS Grid Layout With Examples
18 Things That Make Jest the Best React Testing Framework
/Creating an Image Editor Using CamanJS: Layers, Blend Modes, and Events
/New Short Course: Code a Front-End App With GraphQL and React
/Creating an Image Editor Using CamanJS: Applying Basic Filters
/Creating an Image Editor Using CamanJS: Creating Custom Filters and Blend Modes
/Modern Web Scraping With BeautifulSoup and Selenium
/Challenge: Create a To-Do List in React
1 /Deploy PHP Web Applications Using Laravel Forge
/Getting Started With the Mojs Animation Library: The Burst Module
/A Gentle Introduction to Higher-Order Components in React: Best Practices
/Challenge: Build a React Component
/Eloquent Mutators and Accessors in Laravel
1 /A Gentle Introduction to Higher-Order Components in React
/Understanding Recursion With JavaScript
/Creating a Blogging App Using Angular & MongoDB: Delete Post
/Creating a Blogging App Using Angular & MongoDB: Edit Post
/Creating a Blogging App Using Angular & MongoDB: Add Post
/Introduction to Mocking in Python
/Creating a Blogging App Using Angular & MongoDB: Show Post
/Creating a Blogging App Using Angular & MongoDB: Home
/Creating Your First Angular App: Implement Routing
/Persisted WordPress Admin Notices: Part 4
/Creating Your First Angular App: Components, Part 2
/Persisted WordPress Admin Notices: Part 3
/Creating Your First Angular App: Components, Part 1
/Persisted WordPress Admin Notices: Part 2
/Creating Your First Angular App: Basics
/Persisted WordPress Admin Notices: Part 1
/Error and Performance Monitoring for Web & Mobile Apps Using Raygun
/Using Luxon for Date and Time in JavaScript
7 /How to Create an Audio Oscillator With the Web Audio API
/How to Cache Using Redis in Django Applications
/20 Essential WordPress Utilities to Manage Your Site
/Beginner’s Guide to Angular 4: HTTP
/Rapid Web Deployment for Laravel With GitHub, Linode, and RunCloud.io
/Beginners Guide to Angular 4: Routing
/Beginner’s Guide to Angular 4: Services
/Beginner’s Guide to Angular 4: Components
/Creating a Drop-Down Menu for Mobile Pages
/Introduction to Forms in Angular 4: Writing Custom Form Validators
/10 Best WordPress Booking & Reservation Plugins
/How to Download Files in Python
/10 Best HTML5 Sliders for Images and Text
/Site Authentication in Node.js: User Signup
/Creating a Task Manager App Using Ionic: Part 2
/Creating a Task Manager App Using Ionic: Part 1
/Introduction to Forms in Angular 4: Template-Driven Forms
/Get Rid of Bugs Quickly Using BugReplay
/Manipulating HTML5 Canvas Using Konva: Part 1, Getting Started
10 Must-See Easy Digital Downloads Extensions for Your WordPress Site
/Understanding ExpressJS Routing
/Inheritance and Extending Objects With JavaScript
/Performant Animations Using KUTE.js: Part 5, Easing Functions and Attributes
/Performant Animations Using KUTE.js: Part 4, Animating Text
/Performant Animations Using KUTE.js: Part 3, Animating SVG
/Performant Animations Using KUTE.js: Part 2, Animating CSS Properties
Performant Animations Using KUTE.js: Part 1, Getting Started
/Single-Page Applications With ngRoute and ngAnimate in AngularJS
/Working With Tables in React, Part Two
/How to Set Up a Scalable, E-Commerce-Ready WordPress Site Using ClusterCS
/Build Web Applications Using Node.js
/New Course on WordPress Conditional Tags
/TypeScript for Beginners, Part 5: Generics
/TypeScript for Beginners, Part 4: Classes
/Building With Vue.js 2 and Firebase
6Best Unique Bootstrap JavaScript Plugins
/Essential JavaScript Libraries and Frameworks You Should Know About
Vue.js Crash Course: Create a Simple Blog Using Vue.js
/Build a React App With a Laravel Back End: Part 2, React
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 5.5 API
/Bulk Import a CSV File Into MongoDB Using Mongoose With Node.js
/API Authentication With Node.js
/Command Line Basics and Useful Tricks With the Terminal
/Learn Computer Science With JavaScript: Part 3, Loops
/Learn Computer Science With JavaScript: Part 4, Functions
/Learn Computer Science With JavaScript: Part 2, Conditionals
Learn Computer Science With JavaScript: Part 1, The Basics
/Create Interactive Charts Using Plotly.js, Part 5: Pie and Gauge Charts
Create Interactive Charts Using Plotly.js, Part 4: Bubble and Dot Charts
/Create Interactive Charts Using Plotly.js, Part 3: Bar Charts
/Create Interactive Charts Using Plotly.js, Part 2: Line Charts
/Create Interactive Charts Using Plotly.js, Part 1: Getting Started
/Getting Started With End-to-End Testing in Angular Using Protractor
/Testing Components in Angular Using Jasmine: Part 2, Services
/Testing Components in Angular Using Jasmine: Part 1
/Creating a Blogging App Using React, Part 6: Tags
/React Crash Course for Beginners, Part 3
/React Crash Course for Beginners, Part 2
/React Crash Course for Beginners, Part 1
/Set Up a React Environment, Part 4
1 /Set Up a React Environment, Part 3
/Set Up a React Environment, Part 1
/Creating a Blogging App Using React, Part 5: Profile Page
/Pagination in CodeIgniter: The Complete Guide
/JavaScript-Based Animations Using Anime.js, Part 4: Callbacks, Easings, and SVG
/JavaScript-Based Animations Using Anime.js, Part 3: Values, Timeline, and Playback
/JavaScript-Based Animations Using Anime.js, Part 2: Parameters
JavaScript-Based Animations Using Anime.js, Part 1: Targets and Properties
/20 Popular WordPress User Interface Elements
/10 Elegant CSS Pricing Tables for Your Latest Web Project
/Getting Started With the Flux Architecture in React
/Getting Started With Matter.js: The Composites and Composite Modules
/Getting Started With Matter.js: The Engine and World Modules
/Getting Started With Matter.js: Introduction
/10 More Popular HTML5 Projects for You to Use and Study
/Iterating Fast With Django & Heroku
/Creating a Blogging App Using React, Part 4: Update & Delete Posts
/Creating a jQuery Plugin for Long Shadow Design
/How to Register & Use Laravel Service Providers
2 /Unit Testing in React: Shallow vs. Static Testing
/Creating a Blogging App Using React, Part 3: Add & Display Post
/Creating a Blogging App Using React, Part 2: User Sign-Up
20 /Creating a Blogging App Using React, Part 1: User Sign-In
/Creating a Grocery List Manager Using Angular, Part 2: Managing Items
/Using Celery With Django for Background Task Processing
/Dynamic Page Templates in WordPress, Part 3
/Creating a Grocery List Manager Using Angular, Part 1: Add & Display Items
/New Course: How to Hack Your Own App
/What Is a JavaScript Operator?
/Building Your Startup: Approaching Major Feature Enhancements
How to Define State With Angular UI-Router
/Dynamic Page Templates in WordPress, Part 2
/Dynamic Page Templates in WordPress, Part 1
1Building Your Startup: Securing an API
/How to Draw Bar Charts Using JavaScript and HTML5 Canvas
/Programming With Yii2: Building Community With Voting, Comments, and Sharing
/How to Work With Session Data in CodeIgniter
/12 Best Tab & Accordion WordPress Widgets & Plugins
1 /How to Use the jQuery Function to Select Elements
/How to Create Animations in AngularJS With ngAnimate
/AngularJS Form Validation With ngMessages
/15 Best PHP Calendar, Booking & Events Scripts
/Building Your Startup: Using Routes for Schedule With Me
/A Quick Guide to Dependency Management With Bower
/Getting Started With Chart.js: Scales
/New Short Course: React State Management With MobX
/Building Your Startup: Leveraging Bootstrap, Ajax, and jQuery
/How to Create a Laravel Helper
/Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts
Getting Started With Chart.js: Radar and Polar Area Charts
/Getting Started With Chart.js: Line and Bar Charts
/How to Handle Errors & Exceptions in the Yii Framework
/Getting Started With Chart.js: Introduction
3 /Building Your Startup With PHP: Bootstrap Your Home Page
/How to Build a User Tour With Shepherd in JavaScript
/Building With the Twitter API: Analyzing Your Followers
/Programming With Yii2: Building a RESTful API
/New Course: How to Use the Google Maps API
/Uploading With Rails and Carrierwave
/Making a Sliding Side Navigation Menu for Responsive Designs
/Building With the Twitter API: Creating Friends to Follow
/Building Your Startup: Running Multiple Domains
/Using the Requests Module in Python
5 /Acuity Scheduling Developer Platform: OAuth, Webhooks, and Reporting
/Decoding the Proxy Class in OpenCart
/Acuity Scheduling: Embedding and Developer Integration
1 /Custom Controllers in OpenCart 2
/Building Your Startup: Error Logging
/Acuity Scheduling’s Developer-Friendly Scheduling Service
/New Short Course: Essential Gulp Tasks
/Add a Website Calendar Using Jalendar 2
/Using the New York Times API to Scrape Metadata
1Make Creating Websites Fun Again With Hugo
/Using Illuminate Database With Eloquent in Your PHP App Without Laravel
New Coffee Break Course: How to Use the Angular 2 HTTP Service
/Get Started Building Your Blog With Parse.js: Migration to Your Own Parse Server
/Adding Custom Fields to Simple Products With WooCommerce
/Using Namespaces and Autoloading in WordPress Plugins, Part 4
New Code eBooks Available for Subscribers
/Understanding Forms and Events in React
/Integrate External Libraries in OpenCart Using Composer
1 /How to Build an Angular 2 Service
7 /Programming With Yii2: Using the Debugger
/20 Best CSS Animations on CodeCanyon
/Creating a Custom WordPress Messaging System, Part 4
/Building Your First Web Scraper, Part 3
/
Cathleen Wonderful, what a website it is! This…
Sharyn Ѕimply a smiling ѵisitant heгe to…
shelby What's up it's me, I am also visiting…
Lottie I read this paragraph completely…