AngularJS Factory Tutorial

Elliot Forbes ⏰ 1 Minutes 📅 Apr 9, 2017

What Are Factories

Services are essentially ways we can share code across our AngularJS applications. Say for instance you have an application that interacts with a RESTful API, you would typically create a factory which would return an object that contains all the functions necessary to interact with that API.

By using a factory object, we can standardise the way we interact with the REST API and reduce the amount of duplicate code we have scattered around our application.

Implementing a Factory

var testApp = angular.module("testApp", []);

testApp.factory("RestService", function($http) {
  var service = {};
  var urlBase = "/api/v1";

  service.getUsers = function() {
    return $http.get(urlBase + "/users");

  service.getUser = function(id) {
    return $http.get(urlBase + "/user/" + id);

  return service;

testApp.controller("testController", [
  function($scope, $log, RestService) {
    var init = function() {
        function successCallback(response) {
        function errorCallback(response) {


Our Index Page

<html ng-app="testApp">
    <title>AngularJS Services Tutorial</title>
    <script src=""></script>
  <body ng-controller="testController">
    <script src="scripts.js"></script>