Sunday, September 3, 2017

Factory in AngularJS

  • A factory is a simple Javascript function which allows you to add some logic before creating the object. It returns the created object.
  • This is a singleton object .
Syntex: module.factory( 'factoryName', function );
Example:



When to use
  • It is recommended to use Factory in all the cases.
  • It lets you execute any of your complex logic before returning the final object. So, use this whenever your service needs to be a little complex.

Service in AngularJS

  • It provides a method to keep data across the lifetime of the Angular app.
  • It provides a method to communicate data across the controllers in a consistent way.
  • This is a singleton object and it is instantiated only once per application.
  • It is used to organize and share data and functions across the application.
  • A service is a constructor function.
  • You don’t need to return a value.
Syntex: module. service(' ServiceName', function );

Example:


When to use
  •  Use it when you just want access to the common data and functionality. In other cases, stick to a factory.
  •  Use it when you want to create a simple service. For anything complex, opt for Factories. Because you don’t want to expose this complexity. This is called abstraction.


difference between value vs constant

1.      Constant's value cannot be change. But value's data can be change.

2.      Constant can be injected anywhere. But value can be injected in controller, service and factory but can't be injected in config.

Constant in AngularJS

  • A constant can be injected anywhere.
  • A constant cannot be intercepted by a decorator that means that the value of a constant should never be changed.
Example:
JS:
       MyApp.constant('ProjectVersion', "1.0.0.0");
       MyApp.constant('ProjectTitle', "Demo");
       MyApp.config(function (ProjectVersion) {
                     var ProjectVersionNew = ProjectVersion ;
          });
       MyApp.controller('constantController', function ($scope,ProjectVersion,ProjectTitle) {
                 $scope.Version=ProjectVersion;
                $scope.title=ProjectTitle;
       });
HTML:
     <div ng-controller="constantController">
              Project Title: {{title}}<br/>
              Project Version: {{Version}}
      </div>

Value in AngularJS

In AngularJS, value is a simple object. It can be a number, string or JavaScript object. It is used to pass values in factories, services or controllers during run and config phase. Value cannot be injected into configurations, but it can be intercepted by decorator means that the value can be changed.

Example:
JS
          // Declare a default for value
MyApp.value('greeting', 'Hello');
// Declare a update value by using decorator
MyApp.config(function ($provide) {
$provide.decorator('greeting', function ($delegate) {
return $delegate + ' World!';
});
});
// bind value in view
MyApp.controller("ValueController", function($scope, greeting) {
$scope.greeting=greeting;
});
HTML
<div ng-controller="ValueController">
<span> bind value in view :</span> {{greeting}}
</div>

Custom Services in AngularJS


There are 5 different ways to create services in AngularJS.
  • Value:
    1. In AngularJS, value is a simple object. It can be a number, string or JavaScript object. It is used to pass values in factories, services or controllers during run and config phase. Value cannot be injected into configurations, but it can be intercepted by decorator means that the value can be changed. Read More
  • Service:
    1. It is used to organize and share data and functions across the application.
    2. Service is a constructor function. Read More
  • Factory:
    1. A factory is a simple Javascript function which allows you to add some logic before creating the object. It returns the created object.
    2. This is a singleton object . Read More
  • Provider:
    1. Use it when you want to configure something and pass it to .config of your module. 
    2. Use it to create configurable factories. You can customise such factories during bootstrap
  • Constant:
    1. A constant can be injected anywhere.
    2. A constant cannot be intercepted by a decorator that means that the value of a constant should never be changed. Read More

Saturday, August 26, 2017

$scope in angularjs

  • The $scope in an AngularJS is a built-in object
  • The $scope is glue between a controller and view (HTML).This transfers data from the controller to view and vice-versa.
  • In the controller, we can attach properties and methods to the $scope object and view can display $scope object data using an expression, ng-model, or ng-bind directive, or binding expression.
  • Each controller of application injects a different $scope object.
Example: 
JS :
MyApp.controller('DemoScope', function ($scope) {
    $scope.DemoName = "Demo scope value";
});
HTML :
    <span class="bi">Demo Controller :</span><br/>
    <div ng-controller="DemoScope">
        <span class="b">Scope value:</span> {{DemoName}}
    </div>

$rootScope in angularjs

  • $rootScope is the parent scope object and it will be single for entire application.
  • The data and methods of $rootScope object will be available to all the controllers.
  • All $scope objects are child objects of $rootScope.
  • The ng-app directive initializes the application.
Example: 
JS :
var MyApp = angular.module("MyApp",[]);
MyApp.controller('DemoRootScope', function ($rootScope) {
    $rootScope.rootScopeName = "Root scope value";
});

MyApp.controller('DemoChildScope', function ($scope,$rootScope) {
    $scope.Name = "scope value";
});

HTML :
    <span class="bi">Sibling Controller1 :</span><br/>
    <div ng-controller="DemoRootScope">
        <span class="b"> Root Scope Name:</span> {{rootScopeName}}
    </div>
    <br/>
    <span class="bi">Sibling Controller2 :</span><br/>
    <div ng-controller="DemoChildScope">
        <span class="b">  Child Scope Name:</span> {{Name}} <br/>
        <span class="b">  Root Scope Name: </span> {{rootScopeName}}
    </div>

Monday, August 14, 2017

Name of property of an object

Use Object.keys to get an array of the properties on an object.

Example:

JAVA SCRIPT:

var StdDetails = {
    StdName: "Mohit",
    StdClass: "MCA"
  };
console.log(Object.keys(StdDetails)); 
console.log("Property Names : " + Object.keys(StdDetails)); 
console.log("Value of 0 index(StdName) property : " + StdDetails[Object.keys(StdDetails)[0]]);


OUTPUT:

  1. ["StdName""StdClass"]
    1. 0:"StdName"
    2. 1: "StdClass"
    3. length:2
Property Names : StdName,StdClass

Value of 0 index(StdName) property : Mohit

filter filters in angular

Select a subset of elements from an array and return the result in a new array.
Syntax:
  {{ filter_expression | filter : expression : comparator : anyPropertyKey}}

expression The predicate to be used for selecting items from array.The final result is an array of those                          elements that the predicate returned true for.
Comparator : Defaults to false.
Example:

In JavaScript:
var myApp = angular.module('myApp', []);
myApp.controller('StdController', function($scope) {
  var StdDetails = [{
    StdName: "Mohit",
    StdClass: "MCA"
  }, {
    StdName: "Amit",
    StdClass: "BSC"
  }, {
    StdName: "Manoj",
    StdClass: "Xii"
  }];
  $scope.StdDetails = StdDetails;
  $scope.flt = function(element) {
    if ($scope.StdName1 == undefined || $scope.StdName1 == "") {
      return true;
    } else {
         var regExp = new RegExp("^" + $scope.StdName1, "gi");
      var val = element.StdName.match(regExp) ? true : false;
      return val;
    }
  };
});
In HTML:
<div ng-controller="StdController">
  <div><b>Filter in filters</b></div>
  <!-- Approch#1 -->
  <hr/> Exact match search:
  <input type="checkbox" ng-model="IsExactMatch" />
  <br/> Entire column search : &nbsp;
  <input type="textbox" value="" ng-model="stdname.$" placeholder="input value" />
  <br/>
  <br/> Student Name column search by HTML:
  <input type="textbox" ng-model="stdname.StdName" placeholder="input value" />
  <hr/>
  <table>
    <tr>
      <th>Student Name </th>
      <th>Class</th>
    </tr>
    <tr ng-repeat="std in StdDetails | filter:stdname:IsExactMatch">
      <td>{{std.StdName}} </td>
      <td>{{std.StdClass}}</td>
    </tr>
  </table>
  <!-- Approch#2 -->
  <hr/>
  <br/> Student Name column search by function:
  <input type="textbox" ng-model="StdName1" placeholder="input value" />
  <table>
    <tr>
      <th>Student Name </th>
      <th>Class</th>
    </tr>
    <tr ng-repeat="std in StdDetails | filter:flt">
      <td>{{std.StdName}} </td>
      <td>{{std.StdClass}}</td>
    </tr>
  </table>
</div>

I created a fiddle here with a demo:
https://jsfiddle.net/8qm45ard/

Sunday, August 13, 2017

Date filters in angular

Format a date to a specified format. 

Syntax:
{{ date_expression | date : format : timezone}}

format(optional) : 
format string can be composed of the following elements:
  • 'yyyy': 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) 
  • 'yy': 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) 
  • 'y': 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) 
  • 'MMMM': Month in year (January-December) 
  • 'MMM': Month in year (Jan-Dec) 
  • 'MM': Month in year, padded (01-12) 
  • 'M': Month in year (1-12) 
  • 'LLLL': Stand-alone month in year (January-December) 
  • 'dd': Day in month, padded (01-31) 
  • 'd': Day in month (1-31) 
  • 'EEEE': Day in Week,(Sunday-Saturday) 
  • 'EEE': Day in Week, (Sun-Sat) 
  • 'HH': Hour in day, padded (00-23) 
  • 'H': Hour in day (0-23) 
  • 'hh': Hour in AM/PM, padded (01-12) 
  • 'h': Hour in AM/PM, (1-12) 
  • 'mm': Minute in hour, padded (00-59) 
  • 'm': Minute in hour (0-59) 
  • 'ss': Second in minute, padded (00-59) 
  • 's': Second in minute (0-59) 
  • 'sss': Millisecond in second, padded (000-999) 
  • 'a': AM/PM marker 
  • 'Z': 4 digit (+sign) representation of the timezone offset (-1200-+1200) 
  • 'ww': Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year 
  • 'w': Week of year (0-53). Week 1 is the week with the first Thursday of the year 
  • 'G', 'GG', 'GGG': The abbreviated form of the era string (e.g. 'AD') 
  • 'GGGG': The long form of the era string (e.g. 'Anno Domini').
    format string can also be one of the following predefined localizable formats:
      
  • 'medium': equivalent to 'MMM d, y h:mm:ss a' for en_US locale (e.g. Sep 3, 2010 12:05:08 PM) 
  • 'short': equivalent to 'M/d/yy h:mm a' for en_US locale (e.g. 9/3/10 12:05 PM) 
  • 'fullDate': equivalent to 'EEEE, MMMM d, y' for en_US locale (e.g. Friday, September 3, 2010) 
  • 'longDate': equivalent to 'MMMM d, y' for en_US locale (e.g. September 3, 2010) 
  • 'mediumDate': equivalent to 'MMM d, y' for en_US locale (e.g. Sep 3, 2010) 
  • 'shortDate': equivalent to 'M/d/yy' for en_US locale (e.g. 9/3/10) 
  • 'mediumTime': equivalent to 'h:mm:ss a' for en_US locale (e.g. 12:05:08 PM) 
  • 'shortTime': equivalent to 'h:mm a' for en_US locale (e.g. 12:05 PM)
Example:

Currency filters in angular

Format a number to a currency format. Default currency symbol is $.

Syntax :
{{ currency_expression | currency : symbol : fractionSize}}

symbol(optional) : Currency symbol or identifier to be displayed.
fractionSize
(optional):Number of decimal places to round the amount to, defaults to default max fraction size for current locale
Example:

number filters in angular

It is use to format a number as a Text.Syntex:
   {{ number_expression | number : fractionSize}}

fractionSize: Number of decimal places to round the number to. If this is not provided then the fraction size is computed from the current locale's number formatting pattern. In the case of the default locale, it will be 3.
Example:














I created a fiddle here with a demo:
https://jsfiddle.net/sk0otnch/