AngularJS select box setting selected valueIt can be accomplished by manipulating the

I am facing an issue with a selectbox populated with options from the backend.

<tr>
    <td class="col-lg-4">Superkund</td>
    <td><select class="form-control input-sm2" ng-model="selectedSupercustomer" ng-options="item as item.namn for item in superkundOptions" ng-change="onChangeSuperCustomer(selectedSupercustomer)"></select></td>
</tr>

 $http.get($rootScope.appUrl + '/nao/abb/getSuperkundData/' + $rootScope.abbForm).success(function(data) {
            $scope.superkundOptions = data;
        });

The challenge I'm facing is that the first row remains empty and I want to replace it with a selected value. I attempted to do so with:

$scope.selectedSupercustomer = "fish"

However, this approach did not yield the desired result. Can anyone offer assistance?

Answer №1

When using the select box, it is important to remember that it works with references. This means that you need to assign the model $scope.selectedSupercustomer to $scope.superkundOptions[ID/INDEX_OF_"fish"].

Answer №2

One way to accomplish this is by using the ng-init directive. Here's an example showing how you can use ng-init to select the first item:

<select ng-init="selectedSupercustomer = superkundOptions[0]" ... ></select>

Check out this JSFiddle Example

Answer №3

If you're interested, here's an example to explore:

HTML:

<div ng-app="myApp" ng-controller="SomeController">
    <div ng-repeat="Person in People">
        <div class="listheader">{{Person.firstName}} {{Person.lastName}}</div>
        <div class="listitem" ng-repeat="Choice in Person.Choices">
            {{Choice.Name}}: 
            <select 
                ng-model="Choice.SelectedOption"                 
                ng-options="choice.Name for choice in Choice.Options track by choice.ID"></select>
            {{Choice.SelectedOption.ID}}
        </div>
    </div>
</div>

JavaScript:

var myApp = angular.module('myApp', []);
myApp.controller("SomeController", function($scope) {
    $scope.People = [{
        "firstName": "John",
        "lastName": "Doe",
        "Choices": [
            {
                "Name":"Dinner",
                "Options":[{Name:"Fish",ID:1}, {Name:"Chicken",ID:2}, {Name:"Beef",ID:3}],
                "SelectedOption":{Name:"Chicken",ID:2}
            },
            {
                "Name":"Lunch",
                "Options":[{Name:"Macaroni",ID:1}, {Name:"PB&J",ID:2}, {Name:"Fish",ID:3}],
                "SelectedOption":""
            }
        ],        
    }, {
        "firstName": "Jane",
        "lastName": "Doe"
    }];
});

CSS:

body{
    font-family: verdana;
    font-size: 10pt;
}

.listheader{
    font-weight: bold;
    text-decoration: underline;
    padding-top: 5px;
}

Here is the link to the code on jsfiddle

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

The xslt code is failing to invoke the JavaScript function

I am currently utilizing xslt for the transformation of xml to html. Below is an example of an .xml file. <ImportOrganizationUtility-logging> <log-session module-name="ImportOrganizationUtility" end="17:54:06" start="17 ...

What is the most effective method in Vue.js for transitioning elements without the need to use v-for and v-if at the

Utilizing v-for to generate multiple <p> elements, each one animating in within a Vue <transition> component if the v-if condition is met. Below is the code snippet: <transition name="fade"> <p v-for="(quote, idx) in game.quot ...

Steps to extract viewmodel information from a specific controller following an ajax request

I am encountering an issue with passing updated data from my controller to the view after making an Ajax call. Here is a simplified version of what I am trying to achieve: Javascript $ANALYZE = $('#submitID'); $ANALYZE.click(function () { ...

leveraging a callback function alongside the useState hook

I'm facing an issue with the change() function. My goal is to call the filteredData() function after the setState operation is completed. Typically, I would use a callback function for this task, but useState doesn't support callbacks. Using useE ...

Error message: A boolean type cannot be used as a function in the fullcalendar ajax call

I have successfully implemented a fullcalendar into my app and have added a method to filter results by user: function filterEventsByProvider(selected_provider) { $('#calendar').fullCalendar('removeEvents'); $('#calendar&a ...

Implementing complex routing with Express.js on top of Node.js

Recently delving into the world of javascript, I have embarked on creating a RESTful API using Node.js and Express.js Here is the breakdown of my directory structure: /server.js /api/api.js /api/location/location.js My goal is to make the API modular, ...

Unable to retrieve private field using a public getter method through a proxy

When retrieving data from a VueX Module using a Getter, the Object is enclosed within a Proxy that triggers the following error: TypeError: attempted to get private field on non-instance when attempting to access a private property with a public getter. ...

"Enhance Your Website with Dynamic Text Effects using JavaScript

Is there a way to continuously animate text during the loading process of an AJAX request? I've tried implementing various methods, such as using a setTimeout function or an infinite loop, but nothing seems to work for repeating the animation once it& ...

Sorting Columns in PrimeVue DataTable by Date and Time

I am using a PrimeVue DataTable () with the following structure: <DataTable :rows = "5" :value = "apiItems" > <Column v-for="data in columns" :field="data.field" :header="data.header&q ...

What is the best way to send information using an array of objects?

In my Angular 5 project, I am using the ngx select dropdown package (https://www.npmjs.com/package/ngx-select-dropdown) and I'm wondering how to pass an array of objects instead of an array of strings. Currently, when I do so, it displays [Object Obje ...

Tips for converting a QR code to data URL encoding to include in a JSON response

I created a nodejs function to encode a QR code and I want to return the result back to the caller function in order to create a JSON response. However, for some reason my code is not returning the data response. Can someone please help me figure out what& ...

Can a custom spellchecking feature be integrated into an HTML textarea?

Question: I am wondering if it is feasible to incorporate a personalized spell checking feature into a Textarea field. Background: Currently, I am utilizing the b-form-textarea component from bootstrap-vue to present a textarea where users can input a li ...

Aframe Descend Rotation

I am currently working on a project in Aframe and I'm looking to implement a control/event that enables an entity to rotate downward. While attempting to create a new animation and add it as a child object to the entity, I have achieved successful re ...

Developing uniform resource locators with jQuery

As I work on developing my webapp, I have made use of the tag in my JSPs to ensure that all links within the application - whether they lead to pages or resources like images and CSS - always stem from the root directory rather than being relative to the ...

The initial row of data does not appear to be exported in the CSV file when using the ng-table-export feature in AngularJS

I have integrated ng-table-export into my project, but I am facing an issue where the first row records are missing when I export the data. Below is a screenshot and snippet of my code, can someone please provide assistance? User Interface Output Exporte ...

Utilizing the datepicker options function within a different function

I'm working on a function that utilizes a promise to retrieve data from an asynchronous ajax call: $("#mySelect").on('change', function() { var mySelectValue = $('#mySelect').val(); var promise = getAvailableDates(mySe ...

Does the positive Z axis move inward in threejs? The behavior of camera.near and camera.far seems strange

My goal is to display only a slice of my 3D object. I have tried setting the orthographic camera's camera.near to 2.0 and camera.far to 1.5, then iterating with values of camera.near = 1.5 and camera.far = 1.0. However, this approach is not yielding t ...

The function is not explicitly declared within the instance, yet it is being cited during the rendering process in a .vue

import PageNav from '@/components/PageNav.vue'; import PageFooter from '@/components/PageFooter.vue'; export default { name: 'Groups', components: { PageNav, PageFooter, }, data() { return { groups: ...

Why is it necessary to include 'export' when declaring a React component?

When working with React (ES6), there seems to be two variations that I encounter: class Hello extends React.Component { ... } and sometimes it looks like this: export class Hello extends React.Component { ... } I'm curious about the significance o ...

Issue with a variable within an *.ejs file

Currently, I am following a guide found at this link, and everything is working smoothly except when I encounter an error on the login screen: ..... 7| >> 8| <% if (message != null) { %> 9| <%= message %> 10| <% } %> 11| message ...