Oct 21, 2017

Textual description of firstImageUrl

Factory and Decorator in AngularJS

Factory pattern is very ubiquitous design pattern which finds its uses in most of the design strategy. In this post we will use factory with Decorator and demonstrate - how decorator can be used along side of factory and provide extra functionality without disturbing cleanness of factory.

We will take user input and in return displays reversed output of that input string. Factory comes into picture to give an instance which contains getter and setter method. We define decorator for this Factory instance and reverse input string set via setter method.

Script for Factory and Decorator:

'use strict'

var app = angular.module('DecoratorApp', []);

app.controller("decoratorController", function($scope, reverseFactory) {
 $scope.reverseCall = function() {
  $scope.outputVal = reverseFactory.getData();

app.factory('reverseFactory', function() {
 var myPrivateData;
 return {
  getData : function() {
   return myPrivateData
  setData : function(data) {
   return myPrivateData = data

/* Decoration created for factory reverseFactory */
app.config(function($provide) {
 $provide.decorator('reverseFactory', function($delegate) {
  $delegate.reverse = function() {
  return $delegate

HTML for input and output  :
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Filter application</title>
<body ng-app="DecoratorApp" ng-controller="decoratorController" ng-cloak>
 <div class="mainBody">
  <div class="mainBodyMinHeight">
   <img ng-src="https://toddmotto.com/img/tags/angularjs.svg"
    <label>Input String: </label>
   <div flex="100">
    <input type='text' ng-model="inputVal" ng-blur="reverseCall()" />
   <hr />
   Reversed String:
   <div flex="100">
 <script src="scripts/decoratorApp.js"></script>


Download complete source code.
Location: Bengaluru, Karnataka, India