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.