Wednesday, 22 March 2017

How to define and use your own services ?


Below are 2 ways to write business logic : without service and with service
See second one to check How to define and use the your own Service.

1. Writing business logic directly in Controller - Without a Service
   Here, Controller is complex and long

JS
app.controller("myController", function ($scope) {
   $scope.transform = function (input) {

      var output = "";
      console.log("Processing inside controller ...");
      for(var i=0; i<input.length; i++) {
         if(input[i] == input[i].toUpperCase()){
            output = output + " ";
         }
         output = output + input[i];           
      }

      return output;

       }
});



HTML
<div ng-controller="myController">
  <input type="text" ng-model="input" />
  <br/> Output :
  <input type="text" ng-model="output" />
  <input type="button" ng-click="transform(input)" value="Transform" />
</div>




2. Writing business logic in Service and call from Controller
   Here, Controller is clean and short. The service is reusable.

JS
app.controller("myController", function ($scope, transformService) {
   $scope.transform = function (input) {

        $scope.output = transformService.process(input);
       }
});



app.factory('transformService', function() {
    return {
        process : function (input) {
           var output = "";
           console.log("Processing inside Service ...");
           for(var i=0; i<input.length; i++) {
              if(input[i] == input[i].toUpperCase()){
                 output = output + " ";
              }
              output = output + input[i];
           }

           return output;
        }
    }; 
});


Service is defined using : 
<module>.factory('<serviceName>',
       function(){ return{
           <FunctionName>:<Function>(<params>) {
               ....
           }
       }; } )

Call service inside controller :
<serviceName>.<FunctionName>(<params>);

No comments:

Post a Comment

Note: only a member of this blog may post a comment.