What is the best way to assign the initial value in a dropdown menu populated by a database table?

I'm new to AngularJS and I need help writing a function that can populate a select element with data from a database table. While I am able to fill the select element, I am struggling to set the default value for it.

Here is my code:

HTML :

<div id="super-regional-modal" ng-controller="RegionalController">
    <form name="regionalform" id="regionalform">
        <div class="form-group">
            <div class="row">
                <div class="input-field col s12">
                    <span style="color:#DA1022;">* </span><label for="regionalInfoTipoRegional">Label Test</label>
                    <select class="form-control" id="regionalInfoTipoRegional" name="regionalInfoTipoRegional" ng-model="regionalInfo.tipoRegional"  ng-init="regionalInfo.tipoRegional = populateSelect('select * from wrk_tests')" ng-options="tiporegional as tiporegional.cidade for tiporegional in populate_select_output track by tiporegional.id" ng-required="true"></select>
                </div>
            </div>
        </div>
    </form>
</div>

Javascript :

'use strict';
angular.module("acsApp").controller("RegionalController",  ["$scope", "$http", "$state", "$stateParams", "$timeout", "$sce", "toaster", function ($scope, $http, $state, $stateParams, $timeout, $sce, toaster){
$scope.populateSelect = function(sqlselect){
    $http.post("modulos/sistema/php/sys/fillDB.php", {"sqlselect" : sqlselect}
    ).success(function(data, status, headers, config){
        $scope.populate_select_output = data.records;
    }).error(function(data, status, headers, config){
        console.error(data);
    });
}

PHP :

    <?php
    header("Access-Control-Allow-Origin: *");
    include($_SERVER["DOCUMENT_ROOT"]."/".explode("/",$_SERVER["PHP_SELF"])[1]."/functions.php");
    include($_SERVER["DOCUMENT_ROOT"]."/".explode("/",$_SERVER["PHP_SELF"])[1]."/clsConnection.php");
    $cls_database   = new Database();
    $db             = $cls_database->getConnection();
    $data           = json_decode(file_get_contents("php://input"));
    $sqlselect      = $data->sqlselect;
    $stmt           = $db->prepare($sqlselect);
    $stmt->execute();
    $num            = $stmt->rowCount();
    $arr            = array();
    if($num>0){
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            extract($row);
            $arr[] = $row;
        }
    }
    header("Content-Type: application/json; charset=UTF-8");
    echo json_encode(['records' => $arr]);
?>

Any assistance would be greatly appreciated. Thank you!

Answer №1

To start, make sure to set an initial value for regionalInfo in your controller like this: $scope.regionalInfo = {};. Next, you can assign any of the retrieved records to regionalInfo.tipoRegional:

'use strict';
angular.module("acsApp").controller("RegionalController",  ["$scope", "$http", "$state", "$stateParams", "$timeout", "$sce", "toaster", function ($scope, $http, $state, $stateParams, $timeout, $sce, toaster){
$scope.regionalInfo = {};
$scope.populateSelect = function(sqlselect){
$http.post("modulos/sistema/php/sys/fillDB.php", {"sqlselect" : sqlselect}
  ).success(function(data, status, headers, config){
    $scope.populate_select_output = data.records;
    $scope.regionalInfo.tipoRegional = $scope.populate_select_output[0]; // or 1, 2, etc...
  }).error(function(data, status, headers, config){
    console.error(data);
  });
}

You can update the ng-init to:

ng-init="populateSelect('select * from wrk_tests')"

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

An unexpected error occurred: "mysqli_real_escape_string() requires the first parameter to be a mysqli object, but instead received null."

I have been struggling with a persistent issue that has left me perplexed. The error message I keep encountering is "mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in." Here's the section of code where the problem arises: ...

Unable to execute 'npm run dev' command on Windows operating system

Running Laravel Version: 5.4.21 Using PHP Version: 7.1.1 node v4.4.5 npm v4.5.0 Encountering issues with npm commands on Windows 7. Whenever the command npm run dev is executed, an error message appears: > @ dev E:\xampp\htdocs\larav ...

Creating an if statement based on the currently chosen option

My angular JS page includes a drop-down list: <div class="col-md-4 fieldMargin"> <div class="dropdownIcon"> <select name="actions" id="actions" ...

Excel sheet upload button in Angular not functioning as expected

My project utilizes the Angular file upload component, which can be found at https://github.com/danialfarid/angular-file-upload Previously, everything was functioning correctly. However, after some refactoring, I seem to have inadvertently caused a breaka ...

Perform encryption and decryption of a JSON file on separate webpages

Situation : Is there a way to encode JSON data in the getuser.php page and then decode it in index.php? In my getuser.php file, I use echo (json_encode($data)); which produces the following example output: { "id": 2, "username": "Teeto", "sur ...

Creating dynamic input fields from an array in PHP

Trying to wrap my head around this concept has been a challenge for me over the past week. I am in need of some guidance. My task is to generate dynamic form fields from PHP arrays. These arrays come in various sizes but are always simple. I want to crea ...

stopping php exec from waiting

I have been trying for some time to make my PHP code run asynchronously. I've come across various posts discussing this topic. My goal is to execute additional formatting in my script but have it return quickly without waiting for the exec command re ...

What could be causing my PHP mail script to report success but fail to deliver the email?

Previously, I have successfully used the same script and AJAX query to manage emails without any issues. However, on this particular site, it seems that the process is not functioning properly. Although the POST request indicates success, no email is being ...

Refreshing the page causes JavaScript to fail loading

Recently, I encountered a puzzling error. Upon visiting this link The carousel fails to load properly near the bottom of the page. However, if you click on the logo or navigate back to the home page, it works fine. Additionally, performing a command + r ...

Implementing file uploads with Bootstrap, jQuery, and Laravel

Looking to incorporate the blueimp jquery file upload feature into my Laravel app. Check it out here: https://github.com/blueimp/jQuery-File-Upload The form is set up and working properly with the plugin, but facing issues with creating server-side script ...

Tips for returning to an ajax request after navigating away from the webpage

Is it possible to resume an ongoing Ajax request after exiting and returning to the webpage? For example, if I start an Ajax request and see a progress bar moving forward, then leave the page and come back later, how can I go back to the active request wit ...

PHP is unable to establish a connection with the Xdebug client within the Docker environment

Recently, I encountered a perplexing issue while using WSL2 with docker-ce installed, running PHP 8 and Xdebug 3. Despite numerous attempts at debugging, it appears that PHP is unable to connect to the Xdebug client for unknown reasons. Surprisingly, when ...

Having trouble inserting data into MySQL with no visible error message

Having trouble creating a student registration page where the data isn't getting inserted into the database and no error message is being displayed. I'm unsure of where the issue lies. Any assistance would be greatly appreciated! Here's the ...

Discover the steps to handle parameters received in a $resource GET request

When working in the controller: MyService.get({queryParameter:'MyQueryParameter'}).$promise.then(function(result){ return result; }; Within my service, I include: $resource('/api/path',{ queryParameter: (function manipulate(quer ...

Determining the quantity of non-countable objects in PHP 7.2

For a while now, I've been utilizing PHP 5.4 in an older project of mine. Recently, I made the decision to upgrade to PHP 7.2 Within my project, there are approximately 800 files, and the previous development team heavily utilized count(). In PHP 5 ...

Troubleshooting session persistence post-redirect

Learning PHP has been quite a journey for me, especially when it comes to working with SESSIONS. I recently started using the Instagram API and managed to successfully authorize an app, redirecting to a page to display content. Organized in my main folde ...

When making a request for "/example.php/" the CSS does not seem to take effect, however, the content is displayed properly

Currently, I am working on a PHP script where I have divided each section into separate .php files and included them using the include() function. Here is an example of how everything is set up in different folders: header.php footer.php etc.. When acc ...

Customize the appearance of each element in ng-repeat individually

In my code, I have implemented an ng-repeat. Each alternate div inside the ng-repeat is supposed to have a different border-color, which is achieved by using the following structure: <div ng-repeat="channel in channelList"> <div ng-style="get ...

``JsViews and AngularJS: A Comparison"

I'm exploring the possibility of creating a single page application and came across jsViews/jsRender which seems very promising as it approaches Beta. As someone new to SPA development, I'm interested in understanding how jsViews stacks up agains ...

I am encountering an unresolved error: [$injector:modulerr] Problem on my AngularJS application related to routing

Attempting to develop an angular application, encountering the following error: The issue is outlined in this link: http://errors.angularjs.org/1.3.13/$injector/modulerr?p0=app&p1=Error%3A%20…ttp%3A%2F%2Flocalhost%3A8888%2FHotelAdmin%2Fjs%2Fangular. ...