Total Pageviews

Sunday 24 February 2019

AngularJS | Filters | Example


Filters are another useful feature of AngularJS. By using this feature we don't need to write our own function to format data as AngularJs has built in feature.

Below are the list of filters which AngularJs provides:
  1. currency Format a number to a currency format.
  2. date Format a date to a specified format.
  3. filter Select a subset of items from an array.
  4. json Format an object to a JSON string.
  5. limitTo Limits an array/string, into a specified number of elements/characters.
  6. lowercase Format a string to lower case.
  7. number Format a number to a string.
  8. orderBy Orders an array by an expression.
  9. uppercase Format a string to upper case.
Let’s create an example here, I am using the currency filter, to turn a number into a properly formatted price, complete with a dollar sign and cents. :

HTML:

<div class="row m-0 justify-content-center">
        <div class="col-6 col-sm-6 col-md-6 col-md-6 mt-3">
            <ul class="list-group">
            <li class="list-group-item  m-1" ng-repeat="list in listItems" ng-click="activeList(list)" ng-class="{active:list.active}">
                <span class="float-left">{{list.name}}</span>
<span class="float-right">{{list.price | currency}}</span>
            </li>
        </ul>
        </div>
       
    </div>
    <div class="row m-0 justify-content-center">
            <div class="col-6 col-sm-6 col-md-6 col-md-6 mb-3">
                    <ul class="list-group">
                            <li class="list-group-item  m-1">
                                <span class="float-left">Total</span>
                <span class="float-right">{{totalAmt() | currency}}</span>
                            </li>
                        </ul>
                        </div> 
    </div>


JS:

ImgApp.controller("homeCtrl", function ($scope, $state, imageViewerFactory) {
   
    $scope.listItems = [{
        name:"Potato",
        price:350
    },{
        name:"Tomato",
        price:250
    },{
        name:"Chips",
        price:150
    },{
        name:"Coke",
        price:50
    },{
        name:"Puffs",
        price:35
    }];

    $scope.activeList = function(status){
        status.active=!status.active;
    };
  
    $scope.totalAmt = function(){
        var totalVal = 0;
      
        angular.forEach($scope.listItems, function(val) {
            if(val.active){
            totalVal += val.price;
        }
          });
          return totalVal;
    }

});


CSS:

.ul li span{
    background-color: #34b4aa;
    border:4px #000 solid;
}


OUTPUT


While running the HTML, when user select the items from the list the total value will update in real time.


Thanks :)


No comments:

Post a Comment

Microsoft Logo using flexbox and Reactjs

 <!DOCTYPE html> <html> <head>     <script src="https://unpkg.com/react@18/umd/react.development.js" crossori...