Tuesday, June 16, 2015

Angular JS Services

  •   In Angular, Services are the business logic can be shared across the controllers.
  •   Services needs to be injected(dependency injection) to make use of it in any component.
  •   Services instantiates only when component demands (Lazy instantiation).
  •   Services are Singleton, single reference shared across the components.
  •   Services can have their own dependencies similar  declaring dependencies in a controller.
 

  <body ng-app="myApp">
     <div ng-controller="myController"> {{message}} <br />
     <input type="text" ng-model="sqr" ng-init="sqr=5"> Square of      <b>{{sqr}}</b> =   {{squareCtrl(sqr)}}
     </div>
  </body>

 
  <script>
  var myApp = angular.module('myApp',[]);
 
     // Service logger to log
     myApp.factory("logger", function() {
       return function(v) {
          console.log(v);
       }
     });
 
     // Square service for square arithmetic operation
     myApp.factory("square", [ "logger", function(logger) {

       return function(v) {
         // Service looger dependency injected to this service   
         logger("Square root for : " + v);
          return v * v;
       }
     }]);
 
    myApp.controller('myController', ['$scope', 'square', function($scope, square) {
 
     //Property to the scope
     $scope.message = 'Hello!';
   
     //Behaviour to the scope
     $scope.squareCtrl = function(v) {
        return square(v);
     };
   
  }]);
  </script>

 

No comments: