我有一个表单,根据用户选择的下拉菜单查找医生。
以下表格:
当用户在下拉列表中选择城市并点击搜索时,它会检索城市内的紧急护理。但是,它重复相同的位置。下面的代码是:
<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>
以下代码显示基于用户选择/输入的结果:
<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&daddr={{e.GoogleParams}}" target="_blank"> {{e.OfficeAddress}}</a><br />
<a class="shiftAddUrgent padding" href="https://maps.google.com?saddr=Current+Location&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>
我想在显示结果之前检查值是否重复。如果他们是重复的信息,我想阻止它。我怎么做到这一点?
以下代码是我用来检索数据的代码。我仍在学习角度,所以如果代码看起来很糟糕或者这是一个简单的解决方案,我会道歉。
(
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();
}
});
答案 0 :(得分:0)
这将根据某个属性删除数组中的对象。所以......
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
}
此外,您还需要在HTML中的ng-repeat中添加track by。您可以使用$ index或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&daddr={{e.GoogleParams}}" target="_blank"> {{e.OfficeAddress}}</a><br />
<a class="shiftAddUrgent padding" href="https://maps.google.com?saddr=Current+Location&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>