Monday, 14 November 2016

Creating Custom service for manipulating string in Angular

Service
It is simply means an object that perform some task.

Use of Service
contains reusable code that can be used at multiple places in a project just by referencing it.

Let's see with an example:

Step 1: This is going to be the structure.Include angular.js or angular.min.js file. The file circled are going to be used


Step 2: Create UsingCustomService.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="AngularModule">
<head>
    <title></title>
    <script src="Scripts/angular.min.js"></script>
    <script src="Scripts/UsingCustomService.js"></script>
    <script src="Service/StringManipulationService.js"></script>
</head>
<body ng-controller="AngularController">
    <table border="1">
        <tr>
            <td>Enter Text :</td>
            <td><input type="text" ng-model="InputText"/></td>
        </tr>
        <tr>
            <td>Text in UpperCase :</td>
            <td><input type="text" ng-model="OutputUpper"/></td>
        </tr>
        <tr>
            <td>Text in LowerCase :</td>
            <td><input type="text" ng-model="OutputLower" /></td>
        </tr>
        <tr>
            <td>Text Length :</td>
            <td><input type="text" ng-model="OutputLength" /></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="button" value="Manipulate String" ng-click="ManipulateString(InputText)" /></td>
        </tr>
    </table>
</body>
</html>

Step 3: Create UsingCustomService.js

/// <reference path="angular.min.js" />
var myapp = angular
    .module("AngularModule", [])
 .controller("AngularController", function ($scope, StringManipulationService) {
     $scope.ManipulateString = function (input) {
     
         var strOutput = StringManipulationService.ManipulatedString(input);//Calling Custom Service Method
         $scope.OutputUpper = strOutput.split(',')[0];
         $scope.OutputLower = strOutput.split(',')[1];
         $scope.OutputLength = strOutput.split(',')[2];
     }

 });


Step 4: Creating custom StringManipulationService.js.

/// <reference path="../Scripts/UsingCustomService.js" />
myapp.factory('StringManipulationService', function () { //Factory is used to create Custom Service
    return {
        ManipulatedString: function (input) {
            if (!input) {
                return input;
            }

            var OutputUpper = "";
            var OutputLower = "";
            var OutputLength = 0;

            OutputUpper = input.toUpperCase();
            OutputLower = input.toLowerCase();
            OutputLength = input.length;
            return OutputUpper + "," + OutputLower + "," + OutputLength;
        }
    }
});


Step 8: Let's run the application. Enter text and click on Manipulate String.




0 comments:

Post a Comment