default choice in dropdown menus

I need to populate my option fields with data retrieved from a database. I encountered an error in the console:

Error: [$compile:ctreq] Controller 'select', required by directive 'ngOptions', can't be found!

I am confident that the JSON is sending my data correctly, as I received the following output when I accessed this URL: myaddress.com/forms/usersDB.php?action=get_Logins_info

Output:

[{"id":"1","name":"John"},{"id":"2","name":"Julia"}]

Angular Function:

$scope.ChooseLogins = [];
$scope.getLogins = function () {
    $http.get('forms/usersDB.php?action=get_Logins_info').then(function (data, status, headers, config) {
        $scope.chooseLogins = data;
        console.log('Retrieved data from server');
        console.log(data);
    }).then(function (data, status, headers, config) {
        console.log("Error in retrieving data from server");
        console.log(data, status);
    });
};
$scope.getLogins();

HTML:

<md-select ng-model="getLogins" ng-options="logins.id for logins in chooseLogins">
    <md-option value="{{logins.id}}">{{logins.name}}</md-option>
</md-select>

Answer №1

According to the comments, it's not possible to use ng-options on elements other than <select>, and since <md-select> isn't a select element, the recommended approach mentioned in the documentation is to utilize ng-repeat on the <md-options>. Here's an example:

<md-select ng-model="login">
    <md-option ng-repeat="logins in chooseLogins" ng-value="logins.id">{{logins.name}}</md-option>
</md-select>

To avoid having an empty option, ensure that the model value is set to the first id in the array. Also, note that using the same name for both the model and function might cause conflicts.

Check out this Fiddle for a visual demonstration of how to implement it.

Consider updating your code as follows:

$scope.getLogins = function () {
    $http.get('forms/usersDB.php?action=get_Logins_info').then(function (response, status, headers, config) {
        $scope.chooseLogins = response.data;
        $scope.login = $scope.chooseLogins[0].id;
        console.log('Data retrieved from server');
        console.log(data);
    }).then(function (data, status, headers, config) {
        console.log("Error retrieving data from server");
        console.log(data, status);
    });
};

As an additional step, you may want to validate the length of the returned data before assigning it.

Answer №2

Use ng-repeat directive to repeat elements in AngularJS.

<!DOCTYPE html>
<html>

  <head>
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/angular-material/1.0.6/angular-material.min.css" />
    
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic">
    <link rel="stylesheet" href="style.css" />
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-animate.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-route.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-aria.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-messages.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-material/1.0.9/angular-material.js"></script>
    <script>
    (function () {
  'use strict';

    angular
      .module('MyApp', ['ngMaterial'])
    .controller('AppCtrl', function($interval, $mdDialog) {
      var vm = this;        
vm.chooseLogins = [{"id":"1","name":"John"},{"id":"2","name":"Julia"}];
    });

})();
</script>
  </head>

  <body>
    <div ng-controller="AppCtrl as ctrl" 
        ng-app="MyApp"
        >
      
     
     <p>{{ctrl.chooseLogins}}</p><br>
      <md-input-container>
        <label>Choose name...</label>
      <md-select ng-model="getLogins">
    <md-option ng-repeat="logins in ctrl.chooseLogins" ng-value="logins.id">{{logins.name}}</md-option>
</md-select>
</input-container>
<p>{{getLogins}}</p>
    </div>
    
    
  </body>
  

</html>

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

error message: The file you are trying to access does not exist due to the

I seem to be facing an issue with my package.json file. I am trying to include a new "command" in a correctly written package. Specifically, I am looking to add a command that will load test data, so I updated the scripts section as follows: "load-test-da ...

When accessing the JavaScript date object, no output is being returned

I have a calendar layout consisting of floated div elements, rather than using an actual <table>. My goal is to allow the user to click anywhere on a row to add a new booking. The challenge lies in accurately calculating the time at which they clicke ...

Generating a Personalized XML Format Using Information from a Single MySQL Table Row by Row

If anyone can assist with this, I would greatly appreciate it: <warehouse> <frontbay> </frontbay> <bayrow> <bay> </bay> <bay> ...

Is there a way to incorporate the use of quotation marks within the ng-bind directive in AngularJS?

Is there a way to insert phoneNo["phoneno"] into an HTML input using the ng-bind directive in Angular? While {{phoneNo["phoneno"]}} can display the data, it results in a syntax error when I try to put it like this: <input class="form-control" type="t ...

The event listener activates multiple times on HTML pages that are dynamically loaded with AJAX

Javascript utility function: // This event listener is set using the on method to account for dynamic HTML $(document).on('click', '#next_campaign', function() { console.log('hello'); }); Website layout: <script src=&q ...

AngularJS $resource doesn't play well with Symfony Forms

I am facing an issue with my AngularJS application that is connected to a RESTful Symfony app. The problem arises when trying to POST users (for example, using /api/users/123). When sending a POST request, Symfony Form expects the following structure: { ...

Issue with Bootstrap jQuery dynamic table edit/delete/view button functionality not functioning as expected

Could really use some assistance with this issue. I have a DataTable that includes a button in the last column which offers options like Edit/Delete/View. When clicked, it should delete the entire row. However, I'm struggling to access the current ele ...

Various outcomes were calculated for multiple Vue.js inputs

I am facing an issue with multiple dynamically added search forms on my webpage. Currently, when a user performs a search on one form, all inputs are being searched instead of just the relevant one. Below is the HTML Code for reference: <div class="ro ...

Retrieving CSV information from several files within a JavaScript directory

Currently, I am attempting to retrieve data from numerous CSV files using 'csvtojson'. Firstly, I gathered an array of file names in a specific directory. Then, I used a forEach loop to extract data from various CSV files and convert it to JSON ...

How can we enhance the efficiency of rendering text on the screen?

Imagine having a <p> tag inside a <div> with specific properties: div { height: 100px; width: 100px; overflow: hidden; } My goal is to continuously add words to the <p> tag until an overflow is detected, meaning stop when the f ...

SCRAM-SERVER-FIRST-MESSAGE: The client's password is required to be in string format

After researching documentation from various sources on a similar issue, I have not been successful in resolving this specific error within my code. throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string') ^ ...

Display Image Automatically Upon Page Opening

Currently, I have an HTML file that includes the following code: <img src="(Image from file)" alt="Raised Image" class="img-raised rounded img-fluid"> I am attempting to retrieve the image from a file when the webpage loads using the server.js file ...

What is the best way to transmit two distinct sets of data from a child component to the v-model of a parent component?

Currently, I am working on a project using vuejs 2 and typescript. In this project, I need to pass two different sets of data - data and attachments - within the parent component. I am utilizing vue-property-decorator for this purpose. However, I am facing ...

Attempting to send a POST request, only to be informed by the form that it is devoid of

I have been struggling with this problem for some time now. I implemented the category_create_post functionality in the categoryController, and everything seems to be set up correctly. I also configured the category_form.ejs to accept user input. However, ...

Exploring the next() function in the Next JS API: A practical guide similar to Express JS

When creating an API in Next JS, I encountered an issue while passing three parameters to my API function (req, res, next). Take a look at the code snippet below: import catchAsyncErrors from "../../../middleware/catchAsyncErrors.js"; import conn ...

Is JavaScript generating a random sequence by dynamically adding fields?

I'm encountering an issue with my button that adds a set of text fields every time I click on the Add More button. The problem is that when I add new text fields, they are appended above the Add More button. Then, pressing the button again adds more t ...

My Ajax script is not recognizing the select tag value?

I am struggling with an ajax script that is supposed to send data from a contact form to a PHP script. The main issue I'm facing is that I can't seem to retrieve the value from the "select" tag. My knowledge of JavaScript/ajax is limited, so plea ...

Keeping firebase auth while removing firestore from Vue project

I have recently made the switch from Firestore to MongoDB, and I am currently in the process of removing references to Firestore in my App.vue file. However, I am still utilizing Firebase authentication. Upon checking the console error message, I came acr ...

One file successfully imports a dependency, while the other file does not seem to recognize it

I'm diving into the world of Vuex, exploring how to create an auth module. I came across some examples that I'm trying to implement, but I've hit a roadblock when attempting to use axios in my store. My store is structured with separate file ...

What steps can I take to troubleshoot the "Element type is invalid" error in my React application?

I am currently restructuring my initial code for better organization. Click here to view the code on CodeSandbox. However, I'm facing issues with integrating child components into my code. For example, in this instance, I showcase how I import a chi ...