0

I have a form that looks up doctors based on the drop downs that the user selects.

Form below:

enter image description here

When the user selects a city on the drop down and clicks search, it retrieves the Urgent Care within the city. However, it is repeating the same location. Code below is the form:

<div class="panel panel-default">
<div class="panel-body">
    <form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate role="form">
    <div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important"><strong>Search by<br> URGENT CARE NAME AND/OR CITY </strong></div>
        <div class="form-group"><input class="form-control" id="urgentcare" ng-model="searchParam.UrgentCareName" placeholder="Urgent Care Name" type="text" /></div>
        <!---<div class="form-group"><input class="form-control" id="urgentcare" name="Urgent Care Name" onblur="if(this.value === '') this.value = 'Urgent Care Name';" onfocus="if(this.value === 'Urgent Care Name') this.value = '';" type="text" value="Urgent Care Name" /></div>--->

        <div class="form-group">
        <!---<select class="form-control margin-bottom1" id="city" ng-model="searchParam.City" ng-options="City.value for City in Cities">
        <option disabled="disabled" selected="selected" value="">City</option> </select>--->

            <SELECT name="proCity" class="form-control margin-bottom1" placeholder="City" ng-model="searchParam.City">
                   <option disabled="disabled" selected="selected" value="">City</option> 
                   <option value=""></option>
                      <cfoutput query="UCarecityFind">
                      <option value=#officecity#>#officecity#</option>
                    </cfoutput> 
                  </select>

        </div>
       <hr / style="border-width: thick; background-color: black" >
        <div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important"><strong>OR<br> Search by ZIP CODE RADIUS </strong></div>

        <div class="row">
            <div class="col-xs-7 no-right-padding">
                <div class="form-group">
                    <div class="input-group"><select class="form-control" name="distance" ng-model="searchParam.Distance" ng-options="mile.value for mile in miles"><option selected="selected" value=" "></option><option >5</option><option>10</option><option>15</option><option>20</option></select>
                        <div class="input-group-addon">miles</div>
                    </div>
                </div>
            </div>

            <div class="col-xs-5 no-left-padding widthZip">
                <div class="form-group"><input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" type="text" /></div>
            </div>
        </div>


        <div class="form-group"><input class="btn btn-warning btn-block" ng-click="gotoElement('SearchResultsAnchor');" type="submit" value="Search" /></div>
    </form>
</div>

Code below what displays the results based in the selection/input of the user:

<div>
    <nav class="hidden-xs visible-md visible-lg" ng-show="ShowResults"><uib-pagination boundary-links="true" max-size="maxPageNumbersToShow" ng-model="currentPage" total-items="resultsCount"> </uib-pagination></nav>

    <nav class="visible-xs hidden-md hidden-lg" ng-show="ShowResults"><uib-pager ng-model="currentPage" total-items="resultsCount"> </uib-pager></nav>

    <div class="container" id="searchResults" ng-repeat="e in urgentCareCenters" ng-show="ShowResults">
        <div class="row">
            <hr />
            <div class="col-md-12 no-margin">
                <h4>{{e.OfficeName}}</h4>
            </div>
        </div>

        <div class="row">
            <div class="col-md-4"><strong>Address:</strong> <i class="glyphicon glyphicon-map-marker"></i> <a href="https://maps.google.com?saddr=Current+Location&amp;daddr={{e.GoogleParams}}" target="_blank"> {{e.OfficeAddress}}</a><br />
                <a class="shiftAddUrgent padding" href="https://maps.google.com?saddr=Current+Location&amp;daddr={{e.GoogleParams}}" target="_blank">{{e.OfficeCity}}, {{e.OfficeState}} {{e.OfficeZipCode}}</a></div>

            <div class="col-md-4 no-margin padding"><strong>Phone: </strong><i class="glyphicon glyphicon-earphone"></i> {{e.OfficePhone | PhoneNumber}}<br />
                <strong>Office hours: </strong> <i class="glyphicon glyphicon-time"></i> {{e.OfficeHours}}</div>
        </div>
    </div>

    <nav class="visible-xs hidden-md hidden-lg" ng-show="ShowResults">
        <hr /><uib-pager ng-model="currentPage" total-items="resultsCount"> </uib-pager></nav>
</div>

I would like to check, before the results are displayed, if the values are repeating. If their is information that is repeating, I would like to prevent that. How would I achieve this?

The code below is what I use to retrieve the data. I am still learning angular so I do apologize if the code looks awful or if this is a simple solution.

(
function(){
    var $scope, $location;
    var urgentCareApp = angular.module('urgentCareApp',['ui.bootstrap']);

    urgentCareApp.controller('UrgentCareController',function($scope,$http,$location,anchorSmoothScroll){
        $scope.Lang = 'initVal';
        $scope.ShowResults = false;
        $scope.ShowDesc = true;
        $scope.NoResults = false;
        $scope.currentPage = 1;
        $scope.maxPageNumbersToShow = 10;
        $scope.formModel = {};
        $scope.searchMode = 0;
        $scope.miles =  [{'value':'5'},{'value':'10'},{'value':'15'},{'value':'20' }];
        $scope.searchParam = {};

        $scope.searchParam.Distance = $scope.miles[0];
        console.log($scope.searchParam.Distance);
        //$scope.searchParam.Specialty = $scope.Specialties[0];

        $scope.GetCurrentZip = function (){
            try{
                var lon, lat;
                console.log('starting geoposition code.');
                if("geolocation" in navigator){
                    window.navigator.geolocation.getCurrentPosition(function(pos){
                        lat = pos.coords.latitude.toFixed(3);
                        lon = pos.coords.longitude.toFixed(3);
                        console.log(lat + ' ' + lon);
                        $http.get("/includes/remote/ReturnCurrentZipcode.cfm?Lat=" + lat + "&Lon=" + lon)
                        .success(function(response){
                            console.log('Response: ' + response);
                            $scope.searchParam.Zip = response;
                            console.log('object set');
                        })
                    })
                }
                else if($scope.searchParam.Zip != ""){

                }
                else{ console.log('No geolocation'); }
            }
            catch(err) { console.log(err.message); }
        }

        $scope.GetCityList = function (){
            try{
                $http.get("/includes/remote/ReturnUrgentCareCityList.cfm")
                    .success(function(response){
                        $scope.Cities = response.Cities;
                    })
            }
            catch(err){}
        }

        $scope.SearchUrgentCare = function(searchParam){
            try{
                $scope.searchMode = 1;
                var queryString='';
                if($scope.formModel && $scope.formModel !== searchParam){
                    $scope.resultsCount = 0;
                    currentPage = 1;
                }
                if(searchParam){
                    $scope.formModel = searchParam;
                    for(var param in searchParam){
                        console.log(param + ' ' + searchParam.hasOwnProperty(param) + ' ' + searchParam[param]);
                        if(searchParam.hasOwnProperty(param)){
                            var paramValue = searchParam[param].value ? searchParam[param].value.trim() : searchParam[param].trim();
                            if (paramValue.length > 0)
                                queryString += param + '=' + paramValue + '&';
                        }
                    }
                }
                console.log(queryString);
                queryString= '?' + queryString + 'currentpage=' + $scope.currentPage;

                $http.get("/includes/remote/ReturnUrgentCareList.cfm" + queryString)
                .success(function(response){
                    $scope.urgentCareCenters = response.UrgentCareCenters;
                    $scope.resultsCount = response.rowCount;
                    if (!$scope.urgentCareCenters){
                            $scope.NoResults = true;
                            $scope.ShowResults = false;
                            $scope.ShowDesc = false;
                        }
                    else{
                            $scope.NoResults = false;
                            $scope.ShowResults = true;
                            $scope.ShowDesc = false;
                        }
                })
            }
            catch(err){ alert('No response.: ' + err.message); }
        }

        $scope.$watchGroup(['currentPage'], function(){
            try{
                if($scope.searchMode == 1){
                    $scope.SearchUrgentCare($scope.formModel);
                    }
            }
            catch(err){}
        });


        $scope.GetCityList();
        $scope.GetCurrentZip();

        $scope.gotoElement = function (eID){
            var browserWidth = screen.availWidth;
            if (browserWidth < 768)
                anchorSmoothScroll.scrollTo(eID);
        };

    });

    urgentCareApp.service('anchorSmoothScroll', function(){
        this.scrollTo = function(eID) {

            // This scrolling function 
            // is from http://www.itnewb.com/tutorial/Creating-the-Smooth-Scroll-Effect-with-JavaScript

            var startY = currentYPosition();
            var stopY = elmYPosition(eID);
            var distance = stopY > startY ? stopY - startY : startY - stopY;
            if (distance < 100) {
                scrollTo(0, stopY); return;
            }
            var speed = Math.round(distance / 100);
            if (speed >= 20) speed = 20;
            var step = Math.round(distance / 25);
            var leapY = stopY > startY ? startY + step : startY - step;
            var timer = 0;
            if (stopY > startY) {
                for ( var i=startY; i<stopY; i+=step ) {
                    setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
                    leapY += step; if (leapY > stopY) leapY = stopY; timer++;
                } return;
            }
            for ( var i=startY; i>stopY; i-=step ) {
                setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
                leapY -= step; if (leapY < stopY) leapY = stopY; timer++;
            }

            function currentYPosition() {
                // Firefox, Chrome, Opera, Safari
                if (self.pageYOffset) return self.pageYOffset;
                // Internet Explorer 6 - standards mode
                if (document.documentElement && document.documentElement.scrollTop)
                    return document.documentElement.scrollTop;
                // Internet Explorer 6, 7 and 8
                if (document.body.scrollTop) return document.body.scrollTop;
                return 0;
            }

            function elmYPosition(eID) {
                var elm = document.getElementById(eID);
                var y = elm.offsetTop;
                var node = elm;
                while (node.offsetParent && node.offsetParent != document.body) {
                    node = node.offsetParent;
                    y += node.offsetTop;
                } return y;
            }
        };
    });

    urgentCareApp.directive('allowPattern',[allowPatternDirective]);
    function allowPatternDirective(){
        return{
            restrict: "A",
            compile: function(tElement, tAttrs){
                return function(scope, element, attrs){
                    element.bind("keypress", function(event){
                        var keyCode = event.which || event.keyCode;
                        var keyCodeChar = String.fromCharCode(keyCode);

                        if(!keyCodeChar.match(new RegExp(attrs.allowPattern, "i"))){
                            event.preventDefault();
                            return false;
                        }
                    });
                }
            }
        }
    }

    urgentCareApp.filter('PhoneNumber', function(){
    return function(phoneNumber){
        var dash = '-';
        var openParen = '(';
        var closeParen = ') ';
        if(phoneNumber){
            var pn = phoneNumber;
            pn = [pn.slice(0, 6), dash, pn.slice(6)].join('');
            pn = openParen + [pn.slice(0, 3), closeParen, pn.slice(3)].join('');
            return pn;
            }
        return phoneNumber;
        }
    });

})();

(function($) {
  // @todo Document this.
  $.extend($,{ placeholder: {
      browser_supported: function() {
        return this._supported !== undefined ?
          this._supported :
          ( this._supported = !!('placeholder' in $('<input type="text">')[0]) );
      },
      shim: function(opts) {
        var config = {
          color: '#888',
          cls: 'placeholder',
          selector: 'input[placeholder], textarea[placeholder]'
        };
        $.extend(config,opts);
        return !this.browser_supported() && $(config.selector)._placeholder_shim(config);
      }
  }});

  $.extend($.fn,{
    _placeholder_shim: function(config) {
      function calcPositionCss(target)
      {
        var op = $(target).offsetParent().offset();
        var ot = $(target).offset();

        return {
          top: ot.top - op.top,
          left: ot.left - op.left,
          width: $(target).width()
        };
      }
      function adjustToResizing(label) {
        var $target = label.data('target');
        if(typeof $target !== "undefined") {
          label.css(calcPositionCss($target));
          $(window).one("resize", function () { adjustToResizing(label); });
        }
      }
      return this.each(function() {
        var $this = $(this);

        if( $this.is(':visible') ) {

          if( $this.data('placeholder') ) {
            var $ol = $this.data('placeholder');
            $ol.css(calcPositionCss($this));
            return true;
          }

          var possible_line_height = {};
          if( !$this.is('textarea') && $this.css('height') != 'auto') {
            possible_line_height = { lineHeight: $this.css('height'), whiteSpace: 'nowrap' };
          }

          var isBorderBox = ($this.css('box-sizing') === 'border-box');
          var isTextarea = $this.is('textarea');

          var ol = $('<label />')
            .text($this.attr('placeholder'))
            .addClass(config.cls)
            .css($.extend({
              position:'absolute',
              display: 'inline',
              'float':'none',
              overflow:'hidden',
              textAlign: 'left',
              color: config.color,
              cursor: 'text',
              paddingTop: !isTextarea && isBorderBox ? '0' : $this.css('padding-top'),
              paddingRight: $this.css('padding-right'),
              paddingBottom: !isTextarea && isBorderBox ? '0' : $this.css('padding-bottom'),
              paddingLeft: $this.css('padding-left'),
              fontSize: $this.css('font-size'),
              fontFamily: $this.css('font-family'),
              fontStyle: $this.css('font-style'),
              fontWeight: $this.css('font-weight'),
              textTransform: $this.css('text-transform'),
              backgroundColor: 'transparent',
              zIndex: 99,
            }, possible_line_height))
            .css(calcPositionCss(this))
            .attr('for', this.id)
            .data('target',$this)
            .click(function(){
                if (!$(this).data('target').is(':disabled')) {
                    $(this).data('target').focus();
                }
            })
            .insertBefore(this);
            $this
                .data('placeholder', ol)
                .on('keydown', function () {
                    ol.hide();
                })
                .on('blur change', function () {
                    ol[$this.val().length ? 'hide' : 'show']();
                })
                .triggerHandler('blur');
          $(window).one("resize", function () { adjustToResizing(ol); });
        }
      });
    }
  });
})(jQuery);

jQuery(document).add(window).bind('ready load', function() {
  if (jQuery.placeholder) {
    jQuery.placeholder.shim();
  }
});
Roberto Flores
  • 775
  • 2
  • 12
  • 46
  • Can you post the JS code that is making the call to get this list. Make sure you block out any API keys or other private information, but without seeing how you are building the `urgentCareCenters` list, it will be hard to help. – Tyler Feb 05 '18 at 22:20
  • Use a filter: https://tutorialedge.net/javascript/angularjs/removing-duplicates-from-ng-repeat/ – IsraGab Feb 05 '18 at 22:22
  • @Tyler: I have added the js code and the builiding of the urgentcarecenters list – Roberto Flores Feb 05 '18 at 22:42

1 Answers1

0

This will remove an object in your array based on a certain property. So...

const removeDuplicates= (myArr, prop) => {
  return myArr.filter((obj, pos, arr) => {
      return arr.map(mapObj => mapObj[prop]).indexOf(obj[prop]) === pos;
  });
}


$http.get("/includes/remote/ReturnUrgentCareList.cfm" + queryString)
  .success(function(response){
    var dupsRemoved = removeDuplicates(response.UrgentCareCenters,'OfficeName');
    $scope.urgentCareCenters = dupsRemoved
    // ... rest of code
   }

Also, you will want to add a track by in your ng-repeat, in the HTML. You can use either $index or an id.

<div class="container" id="searchResults" ng-repeat="e in urgentCareCenters track by $index" ng-show="ShowResults">
    <div class="row">
        <hr />
        <div class="col-md-12 no-margin">
            <h4>{{e.OfficeName}}</h4>
        </div>
    </div>

    <div class="row">
        <div class="col-md-4"><strong>Address:</strong> <i class="glyphicon glyphicon-map-marker"></i> <a href="https://maps.google.com?saddr=Current+Location&amp;daddr={{e.GoogleParams}}" target="_blank"> {{e.OfficeAddress}}</a><br />
            <a class="shiftAddUrgent padding" href="https://maps.google.com?saddr=Current+Location&amp;daddr={{e.GoogleParams}}" target="_blank">{{e.OfficeCity}}, {{e.OfficeState}} {{e.OfficeZipCode}}</a></div>

        <div class="col-md-4 no-margin padding"><strong>Phone: </strong><i class="glyphicon glyphicon-earphone"></i> {{e.OfficePhone | PhoneNumber}}<br />
            <strong>Office hours: </strong> <i class="glyphicon glyphicon-time"></i> {{e.OfficeHours}}</div>
    </div>
</div>
Jeremy
  • 1
  • 1