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() {
  reverseFactory.setData($scope.inputVal);
  reverseFactory.reverse();
  $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() {
   $delegate.setData($delegate.getData().split('')
     .reverse().join(''))
  }
  return $delegate
 })
})

HTML for input and output  :
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Filter application</title>
</head>
<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"
    height="100px">
   <p>
    <label>Input String: </label>
   </p>
   <div flex="100">
    <input type='text' ng-model="inputVal" ng-blur="reverseCall()" />
   </div>
   <hr />
   Reversed String:
   <div flex="100">
    <p>{{outputVal}}</p>
   </div>
  </div>
 </div>
 <script
  src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/
 1.4.3/angular.min.js"></script>
 <script src="scripts/decoratorApp.js"></script>
</body>
</html>

Output:-



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