Select box failing to display default value

I am dealing with a specific data structure:

$scope.personalityFields.traveller_type = [
  {"id":1,"value":"Rude", "color":"red"},
  {"id":2,"value":"Cordial", "color":"yellow"},
  {"id":3,"value":"Very Friendly", "color":"green"},
];     

Also, there is a select box set up like this:

<select map-value name="traveller_type" ng-init="init_select()" class="full-width" ng-model="traveller_type" ng-options="item as item.value for item in personalityFields.traveller_type">
  <option value="" disabled selected> Choose ...</option>
</select>  

I need assistance on how to automatically set the select box value based on a response that correlates to the "value" field within the JSON data. Specifically, if the response indicates "Rude" for traveller_type, then "Rude" should be displayed in the select box. Here is an example of the response object structure:

someObject = {
    traveller_type: "Rude"
}

This information from the response should be reflected in the select box.

Answer №1

If the response returns only a single value ("Rude", "Cordial", or "Friendly"), you will need to adjust the syntax of ngOptions to

ng-options="item.vaue as item.value for item in personalityFields.traveller_type"
(binding item.value to the options).

angular.module("app", [])
  .controller("myCtrl", function($scope) {
    $scope.traveller_type = 'Rude';
    $scope.personalityFields = {
      "traveller_type": [{
          "id": 1,
          "value": "Rude",
          "color": "red"
        },
        {
          "id": 2,
          "value": "Cordial",
          "color": "yellow"
        },
        {
          "id": 3,
          "value": "Very Friendly",
          "color": "green"
        },
      ]
    };
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
  <select map-value name="traveller_type" class="full-width" ng-model="traveller_type" ng-options="
                    item.vaue as item.value for item in personalityFields.traveller_type">
    <option value="" disabled selected> Choose ...</option>
  </select>
  {{traveller_type}}
</div>

Alternatively, if the response returns the entire object (

{"id":1,"value":"Rude", "color":"red"}
), you should adjust the syntax of ngOptions to
ng-options="item as item.value for item in personalityFields.traveller_type track by item.value"
(using track by to compare only the value property).

angular.module("app", [])
  .controller("myCtrl", function($scope) {
    $scope.traveller_type = {
          "id": 1,
          "value": "Rude",
          "color": "red"
        };
    $scope.personalityFields = {
      "traveller_type": [{
          "id": 1,
          "value": "Rude",
          "color": "red"
        },
        {
          "id": 2,
          "value": "Cordial",
          "color": "yellow"
        },
        {
          "id": 3,
          "value": "Very Friendly",
          "color": "green"
        },
      ]
    };
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
  <select map-value name="traveller_type" class="full-width" ng-model="traveller_type" ng-options="
                    item as item.value for item in personalityFields.traveller_type track by item.value">
    <option value="" disabled selected> Choose ...</option>
  </select>
  {{traveller_type}}
</div>

Answer №2

There are a few errors in your code snippet, but here is a revised version that can help you achieve your objective:

angular.module('limitToExample', [])
      .controller('ExampleController', ['$scope', function($scope) {
        $scope.serverResponse = {
          "id": 1,
          "value": "Rude",
          "color": "red"
        };
        $scope.personalityFields = {

          traveller_type: [{
            "id": 1,
            "value": "Rude",
            "color": "red"
          }, {
            "id": 2,
            "value": "Cordial",
            "color": "yellow"
          }, {
            "id": 3,
            "value": "Very Friendly",
            "color": "green"
          }],
        }

      }]);
<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Example - example-example103-production</title>


  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>



</head>

<body ng-app="limitToExample">
  
  <div ng-controller="ExampleController">
    <select map-value name="traveller_type" class="full-width" ng-model="serverResponse" ng-options="item as item.value for item in personalityFields.traveller_type track by item.value">

</select>

  </div>
</body>

</html>

This method demonstrates one way to set a default value, which can be further tailored based on the server response (if that's your requirement).

I have simply rephrased what @Pengyy has suggested in their answer, so feel free to consider their solution over mine.

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

Is it possible to hide and reveal specific form elements based on the selection of a checkbox?

Having issues with the code provided below, it's not working as expected. Can you help me figure out what I might be missing? HTML: <input id="id_code_col" type="checkbox" name="code_col"></input> SCRIPT: $(document).ready(function(){ ...

Tips on accessing a specific element that has been mapped in React?

TL;DR - I'm struggling to target and open a specific menu from a list generated using map() on an array without a reference. I've encountered an issue with my React.js code that I need assistance with to resolve. The main concept behind this lo ...

Retrieve the present time of an ongoing CSS3 animation

I've been trying to retrieve the current time of a running animation, but I haven't had any luck so far. I can easily grab the start time using: myelement.addEventListener('webkitAnimationStart', function (evt){ console.log(evt.elaps ...

I'm seeking some assistance in resolving my JavaScript issue

Let's create a function known as 'bigOrSmall' that requires one parameter, 'arr', which will contain an array of numbers. Inside the 'bigOrSmall' function, let's define a new array named 'answers'. Next, it ...

"Dynamic value changes in bootstrap multiselect dropdowns triggered by selection in another multiselect dropdown

I am trying to enhance the functionality of my multiselect dropdown in Bootstrap by updating the values based on another multiselect selection. Currently, the code works well with one selection, but as soon as I include the class="selectpicker", ...

Exploring file writing using Node Webkit and JavaScript

When developing my app, I encountered an issue with the 'fs' module not functioning as expected. Despite the code being written to write a file, nothing happens when the app is launched. However, if I start the app using the following command: $ ...

Ways to create space around Navbar MUI for a more balanced design

Currently, I am working on designing a navigation bar using MUI. My goal is to create a navbar with some space on both sides similar to the one seen on If you take a look at Stackoverflow's navbar, you will notice that it also has space on either sid ...

React Navigation ran into an issue with the specified location

It seems that I am encountering an issue where it is displaying a message stating "no routes matched for location '/'". However, the Header file clearly shows that there is a home component defined for this URL. For further clarification, you ca ...

Removing a selected row from a data table using an HTTP request in Angular 2

I am working with a table that has data retrieved from the server. I need to delete a row by selecting the checkboxes and then clicking the delete button to remove it. Here is the code snippet: ...

Exploring Vue's feature of passing props and emitting events within nested components

Within my coding project, I am facing the challenge of properly implementing a parent component containing a form that includes a birthday component. This birthday component consists of two separate components within it. My task is to effectively pass prop ...

When I open Firefox, all I see is a blank page with only the h2 heading displayed

I am trying to print the text "I can print" on a page, but only the title shows up and the rest of the page is blank. What mistake might I be making? <!DOCTYPE html> <html> <head> <title>Object exercise 4</title> </head& ...

Using v-model with the input type files in Vue.js allows for easy two

Is there a way to retrieve data from v-model array in an input type of "file" that allows multiple selections? <input type="file" multiple v-model="modFiles[index]"> <input type="file" multiple v-model="modFiles[index]"> <input type="file" ...

Angular js encountered an issue with an unrecognized provider: $scopeProvider

I've encountered an error while working on my Ionic project. I'm trying to call a factory method from a controller, but it seems to be throwing an unknown provider error. Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope < ...

Transferring information from one page to the next

How can I efficiently transfer a large amount of user-filled data, including images, between pages in Next.js? I've searched through the Next.js documentation, but haven't found a solution yet. ...

What is the easiest way to choose a child vertex with just one click on mxgraph?

I have nested vertices and I'm looking to directly select the child vertex with just one click. Currently, when I click on a child vertex, it first selects the parent vertex instead. It's selecting the parent vertex initially: To select the ch ...

Assign the filename to the corresponding label upon file upload

I've customized my file uploader input field by hiding it and using a styled label as the clickable element for uploading files. You can check out the implementation on this jsFiddle. To update the label text with the actual filename once a file is s ...

Prevent clicking on a specific column in a table using Jquery

Attempting to utilize Jquery for clicking on a table row in order to navigate to a new page. However, encountering an issue with the last column containing a button that redirects to a new page when clicked on the edge. Is there a way to disable the oncl ...

What is causing ui-route to fail in resolving state1 when transitioning from state2?

I have a program that consists of two views (lefthandmenu and content), with modules. When the user selects a module from a combo-list, $state.go() is called with the selected module name, and the views should update accordingly. See code samples below. I ...

Trying to assign a value to a property that is not defined

I'm attempting to initiate the loading and exhibition of a .stl file through three.js by implementing the following code: var stlLoader = new THREE.STLLoader(); stlLoader.load('assets/Cap.stl', function (object){ object.position.y = - 1 ...

Is there a way to personalize the appearance of a specific page title in my navigation menu?

I'm currently working on customizing the menu of my WordPress theme to display a different color for the active page name. Although my CSS code works well for all page names except the current one: .navbar-nav li a { font-family: georgia; fo ...