Use ng-repeat to extract information from an array and populate it into a datalist

I've already tried searching for a solution to my issue on Google, but I couldn't find anything that really helped me. I'm looking to create an input field that also functions like a dropdown. This way, I can either type in my own data or select from the dropdown options. I attempted to use the select element, but then I could only select predefined data and not enter my own. That's why I decided to use datalist instead. My goal is to populate my datalist with data from an array, like this:

index.html

<input type="text" ng-model="model.person.profession" list="professions"/>
<datalist id="professions">
  <option ng-repeat="profession in professions" value="{{profession.id}}">{{profession.name}}</option>
</datalist>

app.js

$scope.professions = [
  {'id':1, 'name':'doctor'},
  {'id':2, 'name':'farmer'},
  {'id':3, 'name':'astronaut'}
];

However, when I try to view my data in the dropdown, it doesn't show up. What am I missing here?

Answer №1

To display the options in a dropdown, you can utilize ng-options. Check out this example for reference.

<select ng-model="selected">
    <option ng-repeat="value in careers" value={{value.code}}>{{value.title}}</option>
</select>

Answer №2

angular.module('myApp', [])
  .controller("dataListController", function ($scope){
 $scope.professions = [
  {'id':1, 'name':'doctor'},
  {'id':2, 'name':'farmer'},
  {'id':3, 'name':'astronaut'}
];
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<main ng-app="myApp">
  <section ng-controller="dataListController">
     <input list="browsers" name="browser">
      <datalist id ="browsers">
        <option ng-repeat="x1 in professions" value="{{x1.name}}">
    </datalist>
    
   
  </section>
</main>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<main ng-app="myApp">
  <section ng-controller="dataListController">
     <input list="browsers" name="browser">
      <datalist id ="browsers">
        <option ng-repeat="x1 in professions" value="{{x1.id}}">
    </datalist>


  </section>
</main>

Answer №3

Make sure to include a Select element before each option. Also, don't forget to add track by $index inside the ng-repeat loop to avoid errors caused by duplicate data.

   <select>
        <option ng-repeat="value in professions track by $index " value="{{value.id}}">{{value.name}}</option>
    </select>

Alternatively, you can use the following code:

 <select>
    <option ng-repeat="(key, value) in professions " value="{{key.id}}">{{value.name}}</option>
</select>

Check out the demo here: http://jsfiddle.net/HB7LU/28745/

Answer №4

Try using ng-value in place of value when dealing with options

<option ng-repeat="job in jobs" ng-value="{{job.code}}">{{job.title}}</option>

Share your plunkr or code snippet

Answer №5

If you want to explore another approach, consider utilizing ngOptions in the following manner:

<select class="form-control" ng-model="selectedOption" ng-options="option.name for option in careers track by option.id">

Answer №6

It is important to use select instead of datalist :

<select>
    <option ng-repeat="(key, value) in careers " value="{{id}}">{{value}}</option>
</select>

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

How can I locate and substitute a specific script line in the header using Jquery?

I need to update an outdated version of JQuery that I have no control over, as it's managed externally through a CMS and I can't make changes to it. But I want to switch to a newer version of JQuery. Here is the old code: <script type="text/ ...

I consistently encounter the error message 'XRWebGLLayer is not defined no-undef' while implementing three.js within react.js to develop a WebXR application

Trying to implement WebXR with Three.js in a React project, encountering the error: 'XRWebGLLayer' is not defined no-undef for baseLayer: new XRWebGLLayer(session, gl) The code works fine in vanilla JavaScript but fails to compile in React. ...

Accessing store in Vue, the getter function returns a value representing whether the user is currently logged

I have the user state stored in my Vue store, but when I try to access it like this: let isLoggedIn = store.getters.isLoggedIn Instead of getting a simple true or false, I see this in the console: ƒ isLoggedIn (state) { return state.user ? true : false ...

Implementing Icons in Custom Headers of AG Grid Using vue js

I am working on implementing a new feature in AG Grid where I want to display an info icon in the header along with a tooltip that appears when the icon is hovered over. I have already created a custom tooltip component that works correctly, but once I a ...

Obtain the URL within each promise

I'm currently utilizing Bluebird.js and the request-promise NPM module. My goal is to be able to access the promise URL or item.transactionID as shown in the code snippet below. After numerous attempts, I have not been successful in achieving this. Ho ...

Exploring jQuery's AJAX capabilities in handling cross-domain requests and implementing Basic Authentication

I attempted the solutions provided in the suggested duplicate question, but unfortunately, they did not yield the desired outcome. I have been struggling to utilize AJAX to POST data to a remote server's API from a local PC client (testing on Chrome ...

jQuery may not function properly in a dynamic content environment

I'm encountering an issue with my web application. I've developed a chat feature using Ajax, and I want it to load when a button is clicked. The functionality works, but the dynamic data loaded doesn't seem to be compatible with jQuery. Aft ...

Methods for adding a line to an array

I am currently working on a loop where I need to populate my array called photos: $scope.photos = []; var str = data.data.Photos; var res = str.split('|'); angular.forEach(res, function (item) { ...

JS/PHP: No error message will be alerted

<script type="text/javascript"> $(function() { $("#continue").click(function () { $.ajax({ type: "POST", url: "dbc.php?check=First", data: {full_name : $('#full_name').val(), usr_email : $('#usr_ema ...

Can I obtain a dictionary containing the connections between labels and phrases from the classifier?

I've implemented a LogisticRegressionClassifier using the natural library for node: const natural = require('natural'); const classifier = new natural.LogisticRegressionClassifier(); classifier.addDocument('category1', 'sent ...

Repeated URL causes Node to redirect

I am currently working on a project that involves redirecting users if they enter a specific URL, especially for redirecting from a Heroku domain. During my testing phase on localhost, I noticed that the redirect URL keeps getting repeated: http://localh ...

Issue with AngularJS: Not able to get second app in template to function properly

I have encountered a puzzling issue with my two nearly identical apps. The first one seems to be running smoothly as expected, while the second one doesn't appear to be executing at all. Here is my code (jsfiddle): <div ng-app="passwdtool" ng-con ...

Issue with Firefox pageMod addon: window.location not functioning properly

I'm developing a unique Firefox Add-on that implements page redirects based on keyboard input. The keyboard detection is functioning properly, however, the redirect functionality seems to be failing. The complete code can be found on GitHub (even thou ...

Unable to detect JavaScript in Chrome Developer Tools

I am experiencing a strange issue where my JavaScript code is not showing in the sources window. When I include a debugger statement in my JS and then reload the page, it successfully breaks and I can view the JavaScript code. However, the tab is labeled ...

Analyzing JavaScript performance without causing your browser to crash

I recently experimented with profiling code and found that the most convenient method, at least on Firefox, was to utilize either console's time/timeEnd functions or profile/profileEnd methods, so I gave both a try. The issue I encountered was the li ...

Is it possible to upload a file using Angular and ASP.NET Web API Core?

I am encountering an issue with CORS policy while making requests. It works fine when the content-type is set to 'application/json'. However, when I try to upload a file using content-type 'multipart/form-data', I receive an error: XML ...

Utilize CSS in your HTML using Express framework

I am attempting to link a css stylesheet to my basic html webpage. I am utilizing parse.com hosting for dynamic webpages that utilize express. There are numerous responses to this question, but none of them have proven successful in my case. I am trying ...

The size of the cursor varies depending on the line it's placed on

I have a content editable div where three lines are separated by BR tags. When I click on the second line, the cursor becomes bigger than that in the first line. .content { line-height: 35px; } <div class="content" contenteditable="true"> ...

Is there a way to append the current path to a link that leads to another URL?

I am currently in the process of separating a website, with the English version being on the subdomain en. and the French version residing on the www. Before making this change, I have a drop-down menu that allows users to select their preferred language ...

Tips for adjusting column positions in a table while maintaining a fixed header and utilizing both horizontal and vertical scrolling

Is there a way to display a table that scrolls both horizontally and vertically, with the header moving horizontally but not vertically while the body moves in both directions? I have been able to shift the position of the columns, however, I am struggling ...