How can I identify the appropriate default option element in AngularJS?

Query: I have a scenario where I need to set the default option in an angular dropdown menu based on values from an array of Person objects. How can I achieve this when initially loading the UI?

http://plnkr.co/edit/hvIimscowGvO6Hje35RB?p=preview

<!DOCTYPE html>
<html>

<head>
<script src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>

<button ng-click="loadData()">Load Data</button>

<ul ng-repeat="person in model.persons" >
  <li>name: {{person.name}}
    <select ng-select
            ng-options="item.name for item in data"
            ng-change="updateName(selectedName)"
            ng-model="selectedName">
    </select>
  </li>
  <li>age : {{person.age}}</li>
  <li>sex : {{person.sex}}</li>
</ul>

<script>

  var app=angular.module("app",[]);

  app.controller("test",function($scope){
    $scope.model={};
    $scope.model.persons=[];
    $scope.updateName=function(item){
      this.person.name = item.name;
    }
    $scope.data=[{name:'bob'},{name:'Sal'},{name:'Lee'},{name:"Fred"}];

    $scope.loadData=function(){

      $scope.model.persons=[{name:'bob',age:24,sex:'Yes Please'},
                      {name:'Sal',age:29,sex:'Not Today'},
                      {name:'Lee',age:34,sex:'If I must'}];

    }

  });

  angular.bootstrap(document,["app"]);

</script>

Answer №1

If you're looking to mix things up a bit, you might want to try a slightly altered method using ng-repeat for options and ng-selected to highlight a chosen option:

<select ng-model="person.name">
    <option
            ng-repeat="item in data"
            ng-selected="item.name == person.name"
            ng-model="person.name">
        {{item.name}}
    </option>
</select>

Check it out here: http://plnkr.co/edit/gOO3iTXFFNWzFVMZv9GJ?p=preview

Answer №2

There have been a couple of adjustments:

<ul ng-repeat="person in model.persons" ng-init="selectedName = person.name">

ng-options="item.name as item.name for item in data"

Check out the updated version here

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

What is the best way to implement a CSS transition for styles that are dynamically created by React?

I have a situation where I am using a button component that is styled based on a theme provided by a context: The code in Button.js looks like: () => { const theme = useContext(themeContext); // { primaryColor: "blue" } return <button className ...

The slider components have an endless loop feature that only runs once before coming to a

I'm working on creating an infinite slider that loops continuously without the need for navigation buttons. Instead, I plan to allow users to control the slider using touch gestures (although this functionality is not yet implemented in the code snipp ...

Need help setting up a time-based query in Laravel? Here's how to schedule it!

I am currently using the following query to update a status value. public function updateStatus(Request $request) { $customer = Customer::findOrFail($request->user_id); $customer->status = $request->status; $customer->new_customer_s ...

Error: The prop type validation failed because a `value` prop was provided to a form field in React-Bootstrap-Typehead component

I am currently using the bootstrap-typehead package from https://github.com/ericgio/react-bootstrap-typeahead and struggling to understand why it's causing issues. Could someone help me identify what's wrong with this code that's triggering ...

Removing the empty option in a select element with ng-model

There's a situation I'm dealing with that involves a select dropdown along with a refresh button and a plus button. The issue arises when clicking the refresh button sets the model to null, while clicking the plus button displays the dropdown wit ...

The ID value did not pick up the number 0 when passed to the next blade after the initial reading

When passing an ID value to another blade file, I encountered an issue where the other blade file did not read the number 0 at the beginning. For example, if I pass the value of 006, when I console log the value in the other blade view, it only shows 6. H ...

Guide on including a JavaScript file in HTML during execution on Node.js

I have developed a basic nodeJs server with the following code in my server.js file: var http = require('http'); var fs = require('fs'); var path = require('path'); var server = http.createServer(function(req, resp){ // P ...

Express server is receiving undefined post parameters from Axios in Vue, even though they are clearly defined in Vue

Within my code, I am utilizing an <img> element as shown below: <img v-bind:word = "thing" @click="action" align="center" src="../assets/pic.png"/> Alongside, there is a method structured in this manner: ...

The automated Login Pop Up button appears on its own and does not immediately redirect to the login form

Hey guys, I'm struggling with modifying the jquery and html to ensure that when the login button is clicked, the login form pops up instead of displaying another login button. Another issue I am facing is that the login button seems to pop up automati ...

The AngularJS price slider may exceed its range if the ng-model is null or below the minimum value

I currently have an rz-slider featured on my webpage that is utilized for gathering the price of a product from the user. In addition to the slider, there are two input fields present which are designated for storing the minimum and maximum values. The ng- ...

The AJAX response is not functioning as expected

I've encountered an issue with my AJAX code for an online food store. Every time I run it, a pop-up message saying something went wrong appears instead of the expected output. I suspect there might be an error in either the connection handlers or the ...

Click on the link within the Checkbox label on MUI

I am working on creating a checkbox for the "Terms of Use," using FormControlLabel to nest a Checkbox. However, I also need to include a link that opens a Dialog component displaying the terms. The challenge is that clicking on the link checks the checkbox ...

What is the best way to save a JavaScript array in HTML5 local storage?

I am looking for a way to store an array of inputs using the local storage feature of HTML5. Currently, I am able to add weight inputs to the array, but they disappear once I refresh the page. Can anyone assist me with this? <!DOCTYPE html> <html ...

What about a sliding element feature?

Is there a popular slider component that many startups are using, or are these types of sliders typically built from scratch? It seems like they are everywhere on startup websites. I would appreciate it if someone could point me in the right direction with ...

Error in React-Native: Unable to locate main project file during the build process

Just integrated cocoapods into a React Native project. After a successful build, RN is throwing this error... https://i.stack.imgur.com/czn2W.png No errors in Xcode during the build process, but Xcode is displaying these warnings https://i.stack.imgur.c ...

Having trouble setting $scope after redirecting to a partial template via routing

Looking to create a website that loads all necessary templates upon the initial visit. Currently, I only have one partial template but plan to add more in the future. Despite having just this one template, I'm struggling with binding the data from my ...

Error: Attempting to assign a value to 'onclick' property of null object [Chrome Extension]

window.onload = function() { document.getElementById('item_save').onclick = function() { var item_name = document.getElementById('item_name').value; var item_size = document.getElementById('item_size').value; v ...

The operation of moveImage does not exist

Currently, I am attempting to incorporate setInterval with my moveImage function in order to modify the position of an image. Here is a snippet of my code: <template> <div class="randImg"> <img v-bind:style="{top: imgTop + 'px&ap ...

Display the page for 10 seconds continuously in a loop

I am currently developing a Node JS guessing game where data is collected on the back-end and sent to the front-end to start the game. The data consists of 10 levels, allowing the game to operate on a single page. Each level lasts for 10 seconds. Once the ...

Visual Studio encountered an issue while attempting to debug on the web server. The remote server has denied access with error code 403, indicating that debugging is currently

How can I successfully run my application from IIS on my local machine? I've created the virtual directory and added the application to it. The application runs properly when launched from IIS, but I encounter errors when trying to run it through VS 2 ...