AngularJS Factory Tutorial Image AngularJS Factory Tutorial

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>
Elliot Forbes

Elliot Forbes
Twitter: @Elliot_f

Hey, I'm Elliot and I've been working on TutorialEdge for the last 4 years! If my work has helped you in any way, shape, or form then please consider supporting my work.

become a patron Buy Me A Coffee