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/


json filters in angular

Format an object to a JSON string.

Example:

limitTo filters in angular

Limits an array/string, into a specified number of elements/characters.

  • Arrays: it returns an array containing only the specified number of items.
  • Strings: it returns a string containing, only the specified number of characters.

Syntax
         {{ Value | limitTo : limit : begin }}

limit : A number, specifying how many elements to return
begin: Optional. A number specifying where to begin the limitation. Default is 0.

Example:

lowercase filters in angular

To convert string to all lowercase characters.

Example:

Uppercase filters in angular

To convert string to all uppercase characters.

Example:

Saturday, August 12, 2017

Order By filter in Angularjs

Order By is used sort an array based on provided expression.

Syntax

   <tr  ng-repeat=arr[] | orderBy : expression : reverse />

Example:



JavaScript
var myApp = angular.module('myApp', []);
myApp.controller('StdController', function($scope) {
  var StdDetails = [{
    StdName: "Mohit",
    StdClass: "MCA"
  }, {
    StdName: "Amit",
    StdClass: "BSC"
  }];
  $scope.StdDetails = StdDetails;
});

HTML
<div ng-controller="StdController">
  <div>Display in Ascending order</div>
  <table>
    <tr>
      <th>Student Name </th>
      <th>Class</th>
    </tr>
    <tr ng-repeat="std in StdDetails | orderBy:'StdName'">
      <td>{{std.StdName}} </td>
      <td>{{std.StdClass}}</td>
    </tr>
  </table>
  <hr/>
  <div>Display in <strong>descending order</strong> By using <strong>(-) minus sign</strong></div>
  <table>
    <tr>
      <th>Student Name </th>
      <th>Class</th>
    </tr>
    <tr ng-repeat="std in StdDetails | orderBy:'-StdName'">
      <td>{{std.StdName}} </td>
      <td>{{std.StdClass}}</td>
    </tr>

  </table>
  <hr/>
  <div>Display in <strong>descending order</strong> By using <strong>reverse arguments</strong></div>
  <table>
    <tr>
      <th>Student Name </th>
      <th>Class</th>
    </tr>
    <tr ng-repeat="std in StdDetails | orderBy:'StdName':true">
      <td>{{std.StdName}} </td>
      <td>{{std.StdClass}}</td>
    </tr>
  </table>
</div>


OUTPUT
















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

Thursday, August 10, 2017

AngularJS Filters and types

Filters is used to format the value or data for display in UI

There are two types filters :
  1. Standard built-in filter
  2. Custom filter
1.Standard built-in filter:

Angularjs provides the following 9 standard built-in filters:
    1. uppercase : To convert string to all uppercase characters. Read more..
    2. lowercase : To convert string to all lowercase characters. Read more..
    3. number : To format a number as a Text.Read more..
    4. date :Format a date to a specified format. Read more..
    5. currency :Format a number to a currency format. Default currency symbol is $. Read more..
    6. orderBy : sort/order an array based on provided expression.It creates an order alphabetically for strings and numerically for numbers. Read more..
    7. filter: To Select a subset of elements from an array and return the result in a new array.Read more..
    8. json : Format an object to a JSON string.Read more..
    9. limitTo : Limits an array/string, into a specified number of elements/characters. Read more..
2. Custom filter :
Sometimes the built-in filters in Angular cannot meet the needs or requirements for filtering output. In such a case a custom filter can be created.
You can make your own filters by registering a new filter factory function with your module:
By using filter factor

Example:
var myApp = angular.module('myApp', []);

myApp.filter('StartWith', function() {
  return function(items, char,columnIndex) {
    if (items == undefined || items == null) {
      return items;
    } else {
      var filtered = [];
      //
      var match = new RegExp(char, 'i');
      for (var i = 0; i < items.length; i++) {
        var item = items[i];
        
        if (match.test(item[Object.keys(item)[columnIndex]].substring(0,1))) {
          filtered.push(item);
        }
      }
      return filtered;
    }
  };
});

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

Angularjs $filter use in a controller

filter formats the value of an expression to be displayed to the user.
You can also use $filter in controllers, services, and directives. For this, inject a dependency with the name Filter to your controller/service/directive.

Step #1: Inject $filter to controller:

myApp.controller('NameController', function($scope, $filter) {

}

Step#2: Then wherever you want to use that filter, just use it like 

$filter('currency')

Step#3:If you want to pass arguments to that filter, do it using separate parentheses:

$filter('currency')(arg1arg2);

arg1 is the array you want to filter on and 
arg2 is the object used to filter.

Example: 
JavaScript:
var myApp = angular.module('myApp', []);
myApp.controller('NameController', function($scope, $filter) {
  $scope.Name = "Mohit";
  $scope.NameUpper = $filter('uppercase')($scope.Name);
  $scope.NameLower = $filter('lowercase')($scope.Name);
  $scope.Currency = $filter('currency')(100, "INR");
});

HTML:

<div ng-controller="NameController">
  <div>Name:{{Name}}</div>
  <div>Name in Upper:{{NameUpper}}</div>
  <div>Name in Lower:{{NameLower}}</div>
  <div>Currency:{{Currency}}</div>
</div>
Code available in https://jsfiddle.net/g2fLzy9L/

Wednesday, August 9, 2017

Sorting objects array in descending/ascending order in javascript


If you want to orderby in javascript file not in HTML.

Example:

JavaScript:

var myApp = angular.module('myApp', []);
myApp.controller('StdController', function($scope, $filter) {
  var StdDetails = [{
    StdName: "Mohit",
    StdClass: "MCA"
  }, {
    StdName: "Amit",
    StdClass: "BSC"
  }];
  var Dscfiltered = $filter('orderBy')(StdDetails, 'StdName', 1);
  $scope.StdDetailsDsc = Dscfiltered;
  var Ascfiltered = $filter('orderBy')(StdDetails, 'StdName', 0);
  $scope.StdDetailsAsc = Ascfiltered;
});

HTML
<div ng-controller="StdController">
  <div>Display in <strong>dscending order</strong></div>
  <table>
    <tr>
      <th>Student Name </th>
      <th>Class</th>
    </tr>
    <tr ng-repeat="std in StdDetailsDsc">
      <td>{{std.StdName}} </td>
      <td>{{std.StdClass}}</td>
    </tr>
  </table>
  <hr/>
  <div>Display in <strong>ascending order</strong></div>
  <table>
    <tr>
      <th>Student Name </th>
      <th>Class</th>
    </tr>
    <tr ng-repeat="std in StdDetailsAsc">
      <td>{{std.StdName}} </td>
      <td>{{std.StdClass}}</td>
    </tr>
  </table>
</div>

 Screen capture of JavaScript file:


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

Dynamic sorting on table header click in Angular


By using of angularjs orderBy filter to sort table data dynamic or user header click event.

Example:
Java Script:
var myApp = angular.module('myApp', []);
myApp.controller('StdController', function($scope) {
  var StdDetails = [{
    StdName: "Mohit",
    StdClass: "MCA"
  }, {
    StdName: "Amit",
    StdClass: "BSC"
  }];
  $scope.StdDetails = StdDetails;
  $scope.SortcolumnName = "StudentName";
  $scope.reverseSort = false;
  $scope.OrderOf = "descending";
  $scope.SortTable = function(colName) {
    $scope.reverseSort = (colName == $scope.SortcolumnName) ? !$scope.reverseSort : false;
    $scope.SortcolumnName = colName;
    $scope.OrderOf = $scope.reverseSort ? "ascending" : "descending";
  }
  $scope.cssHeaderSort = function(colName) {
    if (colName == $scope.SortcolumnName) {
      return $scope.reverseSort ? "arrow-up" : "arrow-down";
    }
    return '';
  }

});

HTML
<div ng-controller="StdController">
  <div>Display in<b> {{OrderOf}} order</b></div>
  <hr/>
  <table>
    <tr>
      <th ng-click="SortTable('StudentName')">Student Name
        <div ng-class="cssHeaderSort('StudentName')"></div>
      </th>
      <th ng-click="SortTable('Class')">Class
        <div ng-class="cssHeaderSort('Class')"></div>
      </th>
    </tr>
    <tr ng-repeat="std in StdDetails | orderBy:SortcolumnName:reverseSort ">
      <td>{{std.StdName}} </td>
      <td>{{std.StdClass}}</td>
    </tr>
  </table>
</div>

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

Monday, August 7, 2017

Controller in Angular

  • It is responsible to control the relation between models and views.
  • It responds to user input and performs interactions on the data model objects.
  • The controller receives input, validates it, and then performs business operations that modify the state of the data model.
  • It is a JavaScript function.
  • A controller is associated with a HTML element with the ng-controller directive.
In JS

Declaration Type #1 
          
 var myController = function(){ 
                                      //Business logic  
               } 
  myApp.controller(“myController”, myController);       

Declaration Type #2          
    myApp.controller(“myController”, function(){
                    //Business logic
                 });

In Html       
  <div ng-controller=‘myController’> </div>


Post method in angularjs by using $http with parameters


Call WebAPI/Controller and Post the object.



Get method in angularjs by using $http with parameters