Skip to content Skip to sidebar Skip to footer

AngularJS: Creating Query Form For Database

So I am having a little problem creating a very simple query form due to my lack of understanding about coding. As you can see in the app.js below, I have FormController, which ret

Solution 1:

Answers may be opinionated since there are multiple ways to accomplish this.

I would advise to restructure html. Have a single controller that wraps the "form" and the contents of SolrController. Also the "form" should really become a <form>. In angular there is a default controller created for this tag and it helps a lot with managing validation and handling submit.

<div class="results" ng-controller="SolrController">
  <form class="queryForm" name="queryForm" ng-submit="submit()">
    <input type="text" class="queryBox" id="mainQueryString" placeholder="Query String" ng-model="fullQuery.queryString"><br />
    <input type="text" class="queryBox" placeholder="Filter Query" ng-model="fullQuery.filterQuery"><br />
    <input type="text" class="queryBox" placeholder="Sort By" ng-model="fullQuery.sortBy"><br />
    <h2>Extract only from rows:</h2>
    <input type="text" class="halfQueryBox" placeholder="Start" ng-model="fullQuery.startRow"><input type="text" class="halfQueryBox" placeholder="End" ng-model="fullQuery.endRow"><br />
    <input type="text" class="queryBox" placeholder="Field List (Separate by comma)" ng-model="fullQuery.fieldList"><br />
    <input type="text" class="queryBox" placeholder="Raw Query Parameters (key1=val1&key2=val2)" ng-model="fullQuery.rawQuery"><br />
    <button ng-disabled="queryForm.$invalid">Submit Query</button>
  </form>
  <ul>
    <li ng-repeat="item in items">
      {{ item.key }} - <em>{{ item.value }}</em>
    </li>
  </ul>
</div>

Mind name attribute for the form. It will help to access the form in the scope. Actually when there is a name angular creates $scope.queryForm in parent controller
By default all buttons (and <input type="submit") on form submit on click. But type="button" will prevent it. So remove it

Controller SolrController. It's inappropriate to perform a request before user had a change to input something. $http.get should work on a click handler which we choose to be submit event.

app.controller('SolrController', function($scope, $http){
    $scope.fullQuery = {};//ng-model will take care of creating all properties
    function jsonUrlGen(){ //same code here
    }
    $scope.submit = function(){
        $http.get(jsonUrlGen())
            .then(function(res){
                $scope.items = res.data;
            });
        });
    };
})

Hope this helps


Post a Comment for "AngularJS: Creating Query Form For Database"