Sam Daniel Sam Daniel - 5 months ago 42
AngularJS Question

Price range in angularjs

This is my controller

$scope.details =
[
{
"Title": "General Admission",
"Image": "/images/img3.jpg",
"MemberPrice": 50,
"NonMemberPrice": 80
},
{
"Title": "Special Event",
"Image": "/images/img3.jpg",
"MemberPrice": 100,
"NonMemberPrice": 130
},
{
"Title": "Birthday Party",
"Image": "/images/img3.jpg",
"MemberPrice": 160,
"NonMemberPrice": 200
},
{
"Title": "Education",
"Image": "/images/img3.jpg",
"MemberPrice": 220,
"NonMemberPrice": 250
},
{
"Title": "Donation",
"Image": "/images/img3.jpg",
"MemberPrice": 100,
"NonMemberPrice": 165
},
{
"Title": "Animal Adoption",
"Image": "/images/img3.jpg",
"MemberPrice": 180,
"NonMemberPrice": 260
},
{
"Title": "Retail",
"Image": "/images/img3.jpg",
"MemberPrice": 210,
"NonMemberPrice": 270
},
{
"Title": "Product",
"Image": "/images/img3.jpg",
"MemberPrice": 250,
"NonMemberPrice": 300
}
];


This is my HTML page

<div class="form-group">
<label class="control-label col-sm-4">Select Price Range</label>
<div class="col-sm-4">
<select class="form-control" ng-options="price for price in priceRange.Min" ng-model="selectedPrice"></select>
</div>
</div>


What I want to do is that, I want to bind the price ranges in 'selectedPrice'. For example 0-100,101-200,201-300 ,and the minimum and maximum value in the price range should be present in the "$scope.details" either memberprice or nonmemberprice.

Answer

This function calculates min and max and determines the ranges based on the details. Working example is available in below plunker. https://plnkr.co/edit/Xops04bg58MT1vz8c4gR?p=preview

$scope.priceRanges = function() {
    var ranges = [],
      min,
      max,
      interval = 50;

    if (!$scope.details || !$scope.details.length) {
      return ranges;
    }

    min = $scope.details[0].MemberPrice;
    max = min;

    angular.forEach($scope.details, findMinMax);

    min = min - (min % interval);
    max = max - (max % interval) + interval;

    $scope.name = min + ' : ' + max;

    for (var i = min; i < max; i += interval) {
      if (i === min) {
        ranges.push(i + ' - ' + (i + interval));
      } else {
        ranges.push((i + 1) + ' - ' + (i + interval));
      }
    }

    return ranges;

    function findMinMax(detail) {
      if (min > detail.MemberPrice) {
        min = detail.MemberPrice;
      }
      if (min > detail.NonMemberPrice) {
        min = detail.NonMemberPrice;
      }
      if (max < detail.MemberPrice) {
        max = detail.MemberPrice;
      }
      if (max < detail.NonMemberPrice) {
        max = detail.NonMemberPrice;
      }
    }
  };