Как проверить, являются ли параметры запроса пустыми с формами AngularJS

У меня есть проект, где я использую параметры запроса, которые передаются на сервер для поиска.

Они передаются с помощью метода $http.get в AngularJS.

Некоторые параметры не требуются для поиска, поэтому я хочу, чтобы их не было в URL, когда они пусты.

Как я могу получить эту функциональность?

Ниже мой код:

    <!DOCTYPE html>
    <html lang="en"  ng-app = "searchApp">

     <script type="text/javascript">
     var searchApp = angular.module("searchApp", []);

     searchApp.controller("searchListingsCtrl", ['$scope', '$http', function($scope, $http) {
     $scope.searchListings = function(){        

     if ($scope.checkIn == '') {}
     var searchListingObj = {
            checkIn : $scope.checkIn,
            checkOut : $scope.checkOut,
            country : $scope.country,
            city : $scope.city,
            state : $scope.state,
            accommodates : $scope.accommodates,

     }

    var res = $http.get('http://www.localhost:8080/messenger/webapi/listings', searchListingObj);
    res.success(function(data, status, headers, config) {
        $scope.message = data;
    });
    res.error(function(data, status, headers, config) {
        alert( "failure message: " + JSON.stringify({data: data}));
    });     
    };
}]);
</script>

<body ng-controller="searchListingsCtrl">

   <form action="/listings" name="listings" ng-submit="searchListings()">
        <input type="text" name="neighborhood" placeholder="Neighborhood:" ng-model="state">    
        <input type="text" name="town" placeholder="Town:" ng-model="city">
        <input type="text" name="country" placeholder="Country:" ng-model="country">            
        People:<select class="peopleSelect" placeholder="People:" ng-model="accommodates"> </select> 
        <input type="text" id="arrival" name="arrival" value="Arrival" ng-model="checkIn">
        <input type="text" id="departure" name="depart" value="Departure" ng-model="checkOut">
        <input type="submit" name="submit" value="Search" id="Search_submit">
    </form>
  </body>

1 ответ

Использовать required атрибут на входах, чтобы предотвратить отправку формы пустыми полями:

<form  ̶a̶c̶t̶i̶o̶n̶=̶"̶/̶l̶i̶s̶t̶i̶n̶g̶s̶"̶  name="listings" ng-submit="searchListings()">
    <input type="text" name="neighborhood" placeholder="Neighborhood:"
           ng-model="fdata.state"  ͟r͟e͟q͟u͟i͟r͟e͟d͟ />    
    <input type="text" name="town" placeholder="Town:" 
           ng-model="fdata.city" ͟r͟e͟q͟u͟i͟r͟e͟d͟ />
    <input type="text" name="country" placeholder="Country:"
           ng-model="fdata.country"  ͟r͟e͟q͟u͟i͟r͟e͟d͟ />            
    People:<select class="peopleSelect" placeholder="People:"
                   ng-model="fdata.accommodates"  ͟r͟e͟q͟u͟i͟r͟e͟d͟ /> 
           </select> 
    <input type="text" id="arrival" name="arrival" value="Arrival"
           ng-model="fdata.checkIn"  ͟r͟e͟q͟u͟i͟r͟e͟d͟ />
    <input type="text" id="departure" name="depart" value="Departure"
           ng-model="fdata.checkOut"  ͟r͟e͟q͟u͟i͟r͟e͟d͟ />
    <input type="submit" name="submit" value="Search" id="Search_submit" />
</form>

Для получения дополнительной информации см. AngularJS Developer Guide - Forms.

Также обратите внимание, как ng-model атрибуты были изменены, чтобы поместить данные в объект JavaScript. Это облегчает отправку:

$scope.fdata = {};
var url = "http://www.localhost:8080/messenger/webapi/listings";

$scope.searchListings = function() {
    var config = { params: fdata };

    $http.get(url, config)
      .then(function(response) {
        $scope.message = response.data;
    })
      .catch(function(response) {
        var data = response.data;
        console.log( "failure message: " + JSON.stringify({data: data}));
        throw response;
    });             

};

Также имейте в виду, что $http .success а также .catch методы устарели и удалены из AngularJS v1.6. Вместо этого используйте .then а также .catch методы.

Другие вопросы по тегам