<div ng-app="myApp">
  <div ng-controller="MainController">I should have a counter which has been counted 3 times. (Count = {{ count1 }})</div>
  <div ng-controller="SecondController">I should have a counter which has been counted 3 times. (Count = {{ count2 }})</div>
</div>
var app = angular.module('myApp', []);
 
// Counter
function Counter(apiToken) {
  this.apiToken = apiToken;
  this.count = 0;
 
  this.inc = function() {
    this.count++;
  }
 
  this.dec = function() {
    this.count--;
  }
}
 
// Create a dependency called clientId
app.value('clientId', 'abc1234567890')
  
// Create a dependency called apiToken which depends on clientId
app.factory('apiToken', ['clientId', function apiTokenFactory(clientId) {
  // Initialization before return
   var encrypt = function(data1, data2) {
    // NSA-proof encryption algorithm:
    return (data1 + ':' + data2).toUpperCase();
  };
 
  var secret = 'this_is_the_secret_string';
  var apiToken = encrypt(clientId, secret);
 
  // This factory provides you the apiToken
  return apiToken;
}]);

// Create a dependency called counter which depends on apiToken
app.factory('counterFactory', ['apiToken', function counterFactory(apiToken) {
  return {
    createCounter: function() {
      return new Counter(apiToken);
    }
  }
}]);
 
app.controller('MainController', ['$scope', 'counterFactory', function MainController($scope, counterFactory) {
  var counter = counterFactory.createCounter();
  counter.inc();
  counter.inc();
  counter.inc();
  counter.inc();
  counter.dec();
  $scope.count1 = counter.count;
}]);

app.controller('SecondController', ['$scope', 'counterFactory', function SecondController($scope, counterFactory) {
  var counter = counterFactory.createCounter();
  counter.inc();
  counter.inc();
  counter.inc();
  counter.inc();
  counter.dec();
  $scope.count2 = counter.count;
}]);
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js