当用户输入邮政编码时如何清除表格?

时间:2016-07-15 23:45:37

标签: javascript angularjs

我是javascript的新手,需要帮助来实现以下功能:当用户输入邮政编码时,表格的任何其他条目都会被删除,邮政编码会用来查找地址。

我该怎么做?以下是我用于获取紧急护理区附近位置的代码:

(
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("/remote/ReturnCurrentZipcode.cfm?Lat=" + lat + "&Lon=" + lon)
                        .success(function(response){
                            console.log('Response: ' + response);
                            $scope.searchParam.Zip = response;
                            console.log('object set');
                        })
                    })
                }
                else{ console.log('No geolocation'); }
            }
            catch(err) { console.log(err.message); }
        }

        $scope.GetCityList = function (){
            try{
                $http.get("/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("/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 = '-';
        if(phoneNumber){
            var pn = phoneNumber;
            pn = [pn.slice(0, 6), dash, pn.slice(6)].join('');
            pn = [pn.slice(0, 3), dash, pn.slice(3)].join('');
            return pn;
            }
        return phoneNumber;
        }
    });

})();

表格:

<div class="panel panel-default">
    <div class="panel-body">
        <form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate="" role="form">
            <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"><select class="form-control" id="city" ng-model="searchParam.City" ng-options="City.value for City in Cities"><option disabled="disabled" selected="selected" value="">City</option> </select></div>

            <hr />
            <div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important">* or Search by Zip code radius *</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"></select>

                            <div class="input-group-addon">miles</div>
                        </div>
                    </div>
                </div>

                <div class="col-xs-5 no-left-padding">
                    <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>

2 个答案:

答案 0 :(得分:0)

不确定您要做什么,但肯定可以使用ngChange指令,因此当用户输入任何内容Zip时,您可以在控制器中执行您想要的操作。< / p>

请参阅演示

(function() {
  "use strict";
  angular.module('app', [])
    .controller('mainCtrl', function($scope, $http) {
      $scope.reset = function() {
        // If you just want to clear the fields do it:
        var zip = angular.copy($scope.searchParam.Zip);
        $scope.searchParam = {};
        $scope.searchParam.Zip = zip;
      }
    });
})();
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>

<body ng-controller="mainCtrl">
  <div class="panel panel-default">
    <div class="panel-body">
      <form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate="" role="form">
        <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">
          <select class="form-control" id="city" ng-model="searchParam.City" ng-options="City.value for City in Cities">
            <option disabled="disabled" selected="selected" value="">City</option>
          </select>
        </div>

        <hr />
        <div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important">* or Search by Zip code radius *</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"></select>

                <div class="input-group-addon">miles</div>
              </div>
            </div>
          </div>

          <div class="col-xs-5 no-left-padding">
            <div class="form-group">
              <input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" ng-change="reset()" 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>
</body>

</html>

答案 1 :(得分:-1)

你应该使用angular $ scope。$ watch或ng-change指令 例如,如果我想在变量$ scope.varA更改时做某事 你可以使用:

$scope.$watch("varA", function(){
     //my code 
     //in your case (type searchParams.Zip where i wrote varA)
     var zip = $scope.searchParams.Zip; //keep before cleaning
     $scope.searchParams = {};
     $scope.searchParams.Zip = zip;
});

或声明一个角度函数并在html输入上使用ng-change指令,其中使用了ng-model作为邮政编码,(将其添加为属性:ng-change =&#34; clean_form();&#34 ;)

$scope.clean_form = function(){
    var zip = $scope.searchParams.Zip;
    $scope.searchParams =  {};
    $scope.searchParams.Zip = zip;
};

表单清理代码来自developer033,我只是想告诉你如何使代码发生