Developing a Database Query Form Using AngularJS

Hey there! I've run into a bit of trouble while trying to create a simple query form. My coding knowledge is not as strong as I'd like it to be, so any help would be greatly appreciated. In the app.js code snippet below, you'll see that I have a FormController that grabs data from the form and passes it to the jsonUrlGen function to generate a custom URL. This URL is then sent to my SolrController, which fetches JSON information from it.

Upon closer inspection, it's clear to me that the structure of my code is flawed. I think I'm missing an app.service that can establish a link between shared variables in my controllers. I am also questioning whether I really need two separate controllers for this task – it just sort of evolved that way during my coding process.

If anyone could point out where I'm going wrong here, I would be incredibly grateful because, as it stands, the current code simply doesn't work.

Thank you.

.HTML FILE

<html ng-app="solrApp">
<head>
    <link link rel="stylesheet" href="bootstrap-3.3.5-dist/css/bootstrap.min.css" />
    <link link rel="stylesheet" href="style.css" />
    <script src="https://code.angularjs.org/1.4.3/angular.min.js"></script>
    <script type= "text/javascript" src="app.js"></script>
</head>
<body>
    <div class="logo"><img src="images/CubedE.png" id="cubedE"/></div>
    <div class = "queryForm" ng-controller="FormController">
        <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 type="button" ng-click="jsonUrlGen()">Submit Query</button>
    </div>
    <div class = "results" ng-controller="SolrController">
        <ul>
            <li ng-repeat="item in items">
                {{ item.key }} - <em>{{ item.value }}</em>
            </li>
        </ul>
    </div>

</body>
</html>

APP.JS

(function(){
var app = angular.module('solrApp', []);

    app.controller('FormController', function($scope) {

        $scope.fullQuery = {
            queryString: '',
            filterQuery: '',
            sortBy: '',
            startRow: '',
            endRow: '',
            fieldList: '',
            rawQuery: ''
        }

        $scope.jsonUrlGen = function(){

            var jsonURL = "http://localhost:8983/solr/core/select?";

            if($scope.fullQuery.queryString !== '') {
                jsonURL =  jsonURL + "q=" + $scope.fullQuery.queryString;  
            }
            else if($scope.fullQuery.filterQuery !== '') {
                jsonURL = jsonURL + "&fq=" + $scope.fullQuery.filterQuery;
            }
            else if($scope.fullQuery.sortBy !== '') {
                jsonURL = jsonURL + "&sort=" + $scope.fullQuery.sortBy;
            }
            else if($scope.fullQuery.startRow !== '') {
                jsonURL = jsonURL + "&start=" + $scope.fullQuery.startRow;
            }
            else if($scope.fullQuery.endRow !== '') {
                jsonURL = jsonURL + "&rows=" + $scope.fullQuery.endRow;
            }
            else if($scope.fullQuery.fieldList !== '') {
                jsonURL = jsonURL + "&fl=" + $scope.fullQuery.fieldList;
            }
            else {
                return "exception thrown";    
            }

            jsonURL = jsonURL + "wt=json";
            return jsonURL;
        };

    });

    app.controller('SolrController', function($scope, $http){
    $http.get($scope.jsonUrlGen)
        .then(function(res){
            $scope.items = res.data;
        });

    });

    })();

Answer №1

There are various ways to achieve the desired outcome, so answers may vary based on opinion.

In my recommendation, it would be beneficial to restructure the HTML code. The suggestion is to have a single controller that encompasses both the "form" and the contents of SolrController. Additionally, transforming the "form" into an actual <form> element would be advantageous. In Angular, this tag automatically creates a default controller that aids in managing validation and handling submit actions.

<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>

Remember to include a name attribute for the form, which will facilitate accessing the form within the scope. When a name is provided, Angular generates $scope.queryForm in the parent controller.
By default, all buttons (and <input type="submit") trigger submission on click. Using type="button" prevents this behavior, so ensure to remove it.

The SolrController should not make requests before users have inputted anything. It's recommended to perform $http.get within a click handler, which in this case is the submit event.

app.controller('SolrController', function($scope, $http){
    $scope.fullQuery = {};//ng-model handles property creation
    function jsonUrlGen(){ //same code here
    }
    $scope.submit = function(){
        $http.get(jsonUrlGen())
            .then(function(res){
                $scope.items = res.data;
            });
        });
    };
})

I trust this guidance proves helpful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The current situation is not effective; it is causing an error saying "Uncaught TypeError: Cannot read property 'substring' of undefined"

Encountering an error "Uncaught TypeError: Cannot read property 'substring' of undefined" while debugging in Chrome Inspector, with the following code: <script type="text/javascript"> $(function countComments() { var mcount = '/ ...

Is it possible to utilize ember-cli solely as a frontend tool, much like how we use JavaScript and jQuery?

Is it feasible to employ ember-cli exclusively as a front-end tool, similar to utilizing JavaScript and jQuery? I am interested in incorporating a reference to ember-cli in my .NET project solely for validation purposes. Is this a viable approach, and an ...

Capture the selected hyperlink and show the corresponding page title in a designated box for reference

I want to track the links that users click on and display them in a box with an image and name of the page. Additionally, I would like to show how long the user spent on each page below the image. The images in the box should also be clickable links to the ...

The briefest series to equate a mathematical expression with a specific target value

While studying eloquent JavaScript, I encountered a program that checks whether any combination of multiplying 3 and adding 5 produces the target value: However, this function does not provide the shortest possible sequence for achieving the target value. ...

Whenever a route is accessed, Angular creates a duplicate of ng-view

Is it common for AngularJS to generate a new ng-view each time a route is accessed, and then remove the previous ng-view? I've noticed that both views are briefly visible on my app, and certain directives that target the top element also seem to be af ...

Having trouble retrieving the $routeParams value within an AngularJs controller?

Here is my configuration: .config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('tab.chats', { url: '/chats/:id', views: { 'tab-chats': { templateUrl: 'templa ...

Attempting to isolate SQL outcome in order to adjust price based on a percentage

I am currently working on a SQL search and results page that displays 3 columns of data: category, number, and price. However, the results are returned all together in one big lump. My goal is to have a dropdown list with percentages, where clicking on one ...

What are the best ways to get HTML tags functioning properly within Angular.js?

When trying to print a response from a different server that contains a lot of HTML code, how can I display it in a single container? In jQuery, you can achieve this with the following code: $("#xyz").html("<h1>Hello World</h1>& ...

Utilizing Angular to Embed SVG Child Components Within Parent SVG Component

Main Component Template: <svg #mainSvg width="1000" height="600"> <app-custom-component></app-custom-component> </svg> Custom Component Template: <svg:image *ngFor="let img of images"></sv ...

Implementing optimal techniques to create a JavaScript file for data retrieval in a Node.js application

I've developed a file specifically for data access purposes, where I'm keeping all my functions: const sql = require('mssql'); async function getUsers(config) { try { let pool = await sql.connect(conf ...

Redirect to login not working in Angular auth guard

Seeking assistance with troubleshooting an issue within my app. I am attempting to implement a feature where, if the user is not logged in and tries to access any URL of the app, they should be redirected to the login page. I have set up an auth guard, bu ...

Display buttons when hovering with React

Seeking assistance with implementing functionality in a React application where buttons for editing and deleting display only when the mouse hovers over the corresponding row. Currently, the implemented code displays these buttons in all rows on hover. Sn ...

Having trouble with PHP not receiving data when using a $.ajax POST request?

I'm facing an issue where my code seems to be correctly passing a JavaScript variable to PHP. On the JavaScript side, everything works fine - I receive success messages and see the data in the network tab. However, on the PHP side, I am unable to retr ...

Initiating the accordion feature requires two clicks and triggers an rotation of the icon

I managed to integrate some code I discovered for a FAQ accordion on my website. I am struggling with getting the title to expand with just 1 click instead of 2. Additionally, I would like the icon to rotate when expanding/collapsing, not just on hover. Be ...

Using jQuery to transfer array values to a different group of elements

Looking for help with this code snippet: jQuery(document).ready(function($) { var i = 0; var values = []; var element = $('.source'); element.each(function(i) { values[i++] = $(this).text(); }); }); I'm tryi ...

What is the process for creating unit tests for a method that utilizes the @Transaction() decorator?

I am currently using NestJS 6 and TypeORM to interact with a MySQL database. While attempting to write unit tests for a method that utilizes the @Transaction() and @TransactionManager() decorators, I encountered the following error message: ConnectionNotF ...

Mastering the Art of Writing an Ajax Post Request

I am attempting to transmit an image URL to a node.js server from some JavaScript using the Ajax POST method. My expectation is for the server to respond with some text, but I'm encountering issues and unsure where the problem lies. Below is the relev ...

Providing real-time results as numbers are added together

I need assistance in calculating a price inclusive of VAT based on a user-entered VAT rate. Is it possible to show the result in an input box dynamically as the user inputs the VAT rate and price, without requiring them to click a button or resubmit the fo ...

The reduce function is displaying an undefined result

Check out this code snippet: const filterByType = (target , ...element) => { return element.reduce((start, next) =>{ if(typeof next === target){ start.push(next) } } , []) } I'm trying to achieve a specific g ...

Preventing Error in D3 Updates Caused by Invalid Path Formats

I'm encountering a problem with the d3 tree layout while dynamically adding nodes. When I add a path symbol to the node based on its type, I receive an error message "invalid path format" during updates. Both the Enter and update methods utilize the ...