Using JSON Object for Default Selection in an Angular Dropdown Menu

Here is some code I have that fills in a specific select item on a webpage:

<select ng-model="activity.selectedParent" ng-options="parent as parent.title for parent in parents track by parent._id"></select><br>

I'm curious if there's a way to set a default option where I can give it a Title and an ID. For example, if the default is selected, then

activity.selectedParent.Title = "None"
and activity.selectedParent.id = 0. Can this be specified within the <select> tag using Angular directives? If not, what is the most effective approach to achieve this?

Answer №1

If you are looking to set an object as selected even if the default option is chosen, there are two ways to achieve this:

  1. Utilize the ngInit directive within your select tag like this:

    ng-init="selectedParent = { '_id': 0, 'title': 'None' };"

  2. You can also initialize your object in the controller:

    $scope.selectedParent = { "_id": 0, "title": "None" };

EDIT:

If you want a default option instead of leaving it blank at the start, you can simply add this element to your existing array by using the unshift method to place it as the first element:

$scope.parents.unshift($scope.selectedParent);

A code snippet demonstrating this:

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

app.controller('mainCtrl', function($scope) {
  $scope.parents = [  
     {  
        "_id":1,
        "title":"first"
     },
     {  
        "_id":2,
        "title":"second"
     },
     {  
        "_id":3,
        "title":"third"
     },
     {  
        "_id":4,
        "title":"four"
     }
  ];

  $scope.selectedParent = {
    "_id": 0,
    "title": "None"
  };

  $scope.parents.unshift($scope.selectedParent);
});
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>

<body ng-controller="mainCtrl">
  <select ng-model="selectedParent" ng-options="parent as parent.title for parent in parents track by parent._id"></select>
  <hr> 
  Selected: <span ng-bind="selectedParent | json"></span>
</body>

</html>

Answer №2

To ensure that the default value you want to set is included in the array used for ng-options, simply add it to the array.

Start by defining the selectedParent variable in the controller

$scope.selectedParent = { "_id": 0, "title": "None" };

Next, insert it at the beginning of the array

$scope.parents.splice(0,0,$scope.selectedParent);

Lastly, assign the ng-model of the select element to ng-model="$scope.selectedParent"

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

Preventing event bubbling/propagation in custom events: a step-by-step guide

Incorporating a module-project from Github into my Angular project, I am able to resize the DOM elements that are displayed on top of a div functioning as a drawing board. To configure my initial rectangles, I am utilizing a combination of mouseDown - mou ...

Improving JavaScript function by restructuring and eliminating conditional statements from within a loop

Looking for advice on how to refactor my function and eliminate the if statement inside the loop. Any suggestions would be helpful as I suspect the else condition is unnecessary. function quantitySum(array) { let sum = 0; for (let i = 0; i < array ...

Utilizing variables as identifiers in React Native programming

Trying to utilize a dynamic name for a property of an object. For instance, within the function provided below, aiming to use the value stored in the variable 'catagoryId' to access the corresponding child element and assign it to the variable c ...

The token endpoint in Nuxtjs auth module's configuration for auth strategies is not being triggered

Our system has two important endpoints, namely /auth and /token. The endpoint /auth is responsible for providing the authorization code required to call /token in order to obtain an access token. The utilization of NuxtJS has made the auth module a prefer ...

Encountering 'Illegal Invocation' error while running a basic script

Exploring the Speech Recognition API has been on my to-do list, so I decided to create a simple page that initiates recognition when clicking on the body element. Here is a snippet from my scripts.js file: var recognition = new window.webkitSpeechRecognit ...

The functions .ajaxStart and .ajaxStop seem to be malfunctioning

Having trouble displaying and hiding a loading gif before and after an Ajax request using ajaxStart and ajaxStop. Here's what I have: HTML: <div id="loading" style="display: none"><img src="loading.gif></div> JS: $("#searchForm") ...

Smooth carousel navigating through dots

I am currently using the slick carousel from http://kenwheeler.github.io/slick, and I am looking for a way to limit the number of dots to 8 even when there are more than 8 slides. The navigation dots should include arrows on the left and right sides to in ...

Interaction between an Android app and a web page

Looking to develop a mobile app capable of sending messages and images to a webpage. Seeking guidance on how to bring this vision to life. Any assistance would be greatly appreciated in achieving this project. ...

What is the best way to extract information from this particular JSON file?

The JSON data is: {"data": [ ["f45dc1c8-b5ef-29ad-c12bc9731ddc1b59", "10002800"], ["1bcf618d-87c3-3542-61abbee73e09a29e", "10040646"], ["c523aa86-2040-2eeb-844c16d61cad94ec", "10009514, ...

Creating a map with multiple markers by utilizing JSON, PHP, and Google Maps API Version 2

I am currently working with Google Maps API V2 (I know, it's outdated but I have to stick with V2 because I am modifying existing code). All the markers on the map are pointing to the correct locations, but there's one infuriating issue that is d ...

The HTML canvas may sometimes produce inaccuracies in the bytes returned by the getImageData function, a phenomenon known as "

I've come across an issue where the getImageData function of an HTML canvas is returning incorrect byte values. To illustrate, I created a 1x1 pixel image using the following Python code: from PIL import Image import numpy as np a = np.array([[[12, ...

Exploring the process of retrieving array elements from an AJAX response transmitted from PHP

Here is an example of jQuery code for an ajax function: $(document).ready(function() { $("#zip_code").keyup(function() { var el = $(this); var module_url = $('#module_url').val(); if (el.val().length === 5) { $.ajax({ ...

Updating HTML in Vue.js with data at a specific index value can be done by targeting

Experimenting with a combination of vue.js and vanilla to create a blackjack game. The card data is stored in the vue data() like this: data(){ return { cards: [ {id: 1, cardName: 'Ace of Spades', cardPic: ' ...

What is the best way to showcase the contents of an array of objects from JavaScript on an HTML page in a dynamic

Looking for guidance in Javascript as a beginner. For an assignment, I need to create two separate JS files and use them to display data dynamically on an HTML page. One JS file, named data.js, contains an array of objects representing a product catalog. T ...

Adjust the font weight to bold for specific sections of the option value within a reactjs component

I have a component that generates a dropdown menu. I want to apply bold formatting to certain text within the dropdown values. Specifically, I need to make the ${dataIdText} text appear in bold within the dropdown menu. Here is a snippet of my code: < ...

Learn how to effortlessly integrate and utilize a bpmn file in a Vue component by leveraging the raw-loader

As a newcomer to bpmn-js, I am facing the challenge of importing and utilizing a .bpmn file within a vue.js component (BPMNViewer.vue). Despite my efforts in researching, I could only find recommendations to use the raw-loader. Consequently, I am currently ...

Webpack 5 is unable to load animated gif files

Hello, I am currently diving into webpack and following the official documentation at https://webpack.js.org/guides/asset-management/#setup. My goal is to incorporate an animated gif using webpack 5. Although the placeholder for the gif is loading, I enco ...

The && symbol in JSONPath: combining conditions efficiently

Here is an example of JSON data taken from the tutorial: { "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", " ...

Auto-fill Textbox from a different Textbox in MVC 4

I am attempting to automatically fill in a textbox based on the value of another textbox, but I am struggling with getting the other textbox to populate. Below is my code - any advice on the best solution would be greatly appreciated. Action Method: [Htt ...

How can we store data coming from PHP using AJAX and update the color of a div whenever new data is inserted?

Hey there, I'm currently working on a project where I need to save values and display them using Ajax after inserting them into a MySQL table using PHP. However, I'm having trouble with the alert function not working as expected. Let me share my ...