Search code examples
angularjsangularjs-ng-formng-submit

Angular JS Process form before submit


I have a scenario as follows :

I have one searchbox and the user can enter two types of queries

Scenario One the Search Starts with i.e. A1234 Scenario Two the search Starts with i.e. B1234

Depending on one or two above I want to hit a different webservice.

Whats the best way to distinguish the search on the above input. Is it when the user clicks on my ng-submit I use a regular expression ?

Or should I have a scope variable on .watch() to find out as the user is typing ?

<form role="form" ng-submit="searchForm.$valid && searchCode()" name="searchForm" novalidate>
     <div class="input-group">
        <input type="text" class="form-control" ng-model="searchQuery" name="searchQuery" required autocomplete="off" spellcheck="false" focus>
          <input type="submit" value="Search" class="btn btn-default btn-sarch-bar">
     </div>
</form>

Solution

  • If the search is activated upon submit-button click, then you can handle the login in the submit function, and hit the proper webservice accordingly. something along these lines:

    <form role="form" ng-submit="submit(searchForm.$valid, data)" name="searchForm" novalidate>
      <div class="input-group">
        <input type="text" class="form-control" ng-model="data.searchQuery" name="searchQuery" required autocomplete="off" spellcheck="false" focus>
        <input type="submit" value="Search" class="btn btn-default btn-sarch-bar">
      </div>
    </form>
    

    submit function:

    $scope.submit = function(isValid, data) {
      if(!isValid) return;
    
      //check data.searchQuery and access the appropriate webservice here
    }
    

    If you're using angularjs 1.3, and you'd like to perform a search upon user interaction with the input, you might be interested in adding a directive to the input element, and use $asyncValidators

    there's a great tutorial by yearofmoo regarding forms and validators using directives.