Tips for pre-selecting default text in ng-select or ng-options component?

I'm new to AngularJS and I've been looking for solutions here without any luck. I have a json file from a controller that I'm displaying in a select element. I want to set the selected value based on the text value. This is my current progress:

HTML:

<div ng-app="userModule" ng-controller="userCtrl">
<div class="row">
    <div class="col-md-6">
        <label>User Name:</label> <br />
        <select ng-model="users.selectedUser" class="form-control" ng-options="item.UserName as item.UserName for item in users.availableOptions"></select>
    </div>        

Controller:

<script>
var _$http;
var _$scope;
var oldUser = @Html.Raw(Json.Serialize(ViewData["UserName"]));
var oldRole = @Html.Raw(Json.Serialize(ViewData["RoleName"]));
angular.module('userModule', [])
    .controller('userCtrl', xConstructor);

function xConstructor($scope, $http) {
    _$http = $http;
    _$scope = $scope;
    $http.get("/RoleManagement/GetUserData").then(xReceive);
    $http.get("/RoleManagement/GetRoleData").then(roleReceive);

    _$scope.submit = function () {
        //alert("Here:" + _$scope.selectedUser);
        $http.get("/RoleManagement/PutUserRoleData?UserId=" + $scope.selectedUser.UserId + "&RoleId=" + $scope.selectedRole.RoleId).then(writeSuccess);
    }

}

function xReceive(userObject) {
    _$scope.users = {
        availableOptions: userObject.data,
        **selectedUser: { UserId: oldId, UserName: oldUser } //What to put here?**
    };

    alert(JSON.stringify(JSON.stringify(_$scope.users.selectedUser));
}
</script>

Any other suggestions on how to achieve this?

Answer №1

The issue stems from not properly associating the model with any element within the array. If you have the user's id that you wish to choose, follow these steps:

function xReceive(userObject) {
        _$scope.users = {
            availableOptions: userObject.data,
            selectedUser: null
        };

        let selectedUser;
        for (let i = 0; i < userObject.data.length; i++) {
          if (userObject.data[i].id === oldId) {
           selectedUser = userObject.data[i];
           break;
          }
        }
        if (selectedUser) {
          _$scope.users.selectedUser = selectedUser;
        }
        alert(JSON.stringify(JSON.stringify(_$scope.users.selectedUser));
    }

Additionally, if you simply want to choose the first user, you can use this:

_$scope.users.selectedUser = _$scope.users.availableOptions[0];

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

Hearken to a Vue event using regular JavaScript

One of my Vue components emits the change event. methods: { onSelect(value) { this.open = false if (value === this.value) return this.$emit('change', value) }, } I have integrated this component into an .astro file ...

What is the best way to redirect to the login page using the PUT method in express.js when the user is not authenticated?

I am encountering an issue where I need to update a database from an AngularJS page using the $http.put method. However, if the session expires, it displays errors on the server. When the put method is triggered, it goes to this route: PUT /api/categorie ...

Disappearance of array data

I have been working on creating an array of objects with nested arrays, but I am facing an issue where data seems to go missing in the final step: const args_arr = []; const options_arr = []; let options = ''; let text = ""; for (let i = 0; ...

jquery monitors an element to see if it contains a particular attribute, then takes action accordingly

I'm attempting to conceal a div when an anchor tag (a) has a particular href, and reveal it when the href is different. This is what I've tried: if($('a[href="#intro"]').not(".active")) { $('.navbar-brand').hide();} else ...

Determining if a field in Angular is empty

I'm new to Angular and have a question about handling input fields. I want an action to occur only if the field contains valid content. Currently, I am instantiating a variable, assigning it to the input, and performing a boolean check in an if state ...

Is there a way to retrieve a specific item from an array using a different method than just its position with jsRender?

I am currently working on rendering JSON data using jsRender. Take a look at the sample JSON data below: "PageContentList": [ { "ContentId": 51, "Title": "60 seconds with Rick", "ContentMediaTypeList": [ { ...

Submitting information to the server utilizing a POST request through jQuery

What I'm attempting to achieve: I am currently working on sending data to my server using the $.post jQuery shortcut. The issue at hand: It seems that my program is not entering my switch case, possibly due to a problem with sending the action prop ...

Is there a way to determine if a JavaScript alert box is currently open in a browser using Ruby and Selenium? If so, what steps can be taken to close

During the process of transitioning between pages with Selenium functions, there are instances where a confirm box appears with options to click OK or cancel. What is the proper way to detect this box and dismiss it? Appreciate the help ahead of time! ...

Switching the navbar state from a regular mode to a collapsed mode can be done manually

I need help with my navbar design: <nav class="navbar fixed-top navbar-expand-sm navbar-light"> <div class="container-fluid"> <button class="navbar-toggler" type="button" data-bs-toggle=&q ...

Jasmine - A guide to error testing techniques

SCENARIO: Hey everyone! I'm currently diving into Jasmine to test my Angular application. I've created a simple function that multiplies two numbers. If the input parameters are not numbers, the function throws an error. Next, I wrote two basi ...

"Troubleshooting: Why is the onError event not triggering

Has anyone else experienced issues with using a third-party API to fetch YouTube thumbnails with higher resolution, sometimes resulting in a code 404 error? I've been trying to replace the image source with a default YouTube thumbnail retrieved from i ...

When using Node.js with Firebase, information is not stored in the session

I've been attempting to implement session management in my application to keep track of user log-ins and other activities. However... Whenever I try the simplest way, I consistently encounter this error: Warning: connect.session() MemoryStore is ...

I'm confused by the function: "sort((a: Article, b: Article) => b.votes - a.votes);"

I'm having trouble grasping the concept of the return statement in sortedArticles(). Can anyone provide me with a resource or explain how this sorting function works? sortedArticles(): Article[] { return this.articles.sort((a: Article, b: Article ...

When navigating back in Next.js, the URL changes but the content remains the same

I'm currently troubleshooting an issue where the content is not updating when I navigate back using the browser's back button or by setting a button with router.back. The URL updates correctly, but the content remains the same. When I refresh the ...

Understanding intricate JSON structures with JavaScript

Here is the JSON structure that I am working with: var data = [ { "country":"Andorra", "code":"AD", "state":[ { "state_code":"AD1", "state_description":"aaAndorra1" }, { " ...

Three.js - implementing a billboard effect that preserves orientation through camera pans

My situation involves a plane geometry that always faces the camera using the following line of code in the update loop: plane.lookAt(camera.position); While I am utilizing OrbitControls to manipulate the camera, the plane successfully maintains its orie ...

What is the reason behind AngularJS consistently selecting the first TD cell?

I'm a beginner in AngularJS and I'm testing my skills by creating a small game. Here's the table structure I have: <table class="board"> <h1>Table</h1> <input type="number" ng-model="val"><button ng-click="ctrl.f ...

Having difficulty identifying the same element during testing

Here is the code snippet I'm working with, which checks for expected text: console.log(typeof browser.getText('.modal.modal--primary.pin-container h1')); expect(browser.getText('.modal.modal--primary.pin-container h1')).toContain( ...

Collecting values using AJAX in Codeigniter from an input file

I have been exploring examples of AJAX code, and I noticed that when using form-data in AJAX, we need to serialize each element individually. While normal data serialization works fine, I encountered an issue when trying to pass the value of an input file ...

The routing functionality in Angular4 encounters issues when the `router.navigate()` method is used within the callback of a

I am currently working on implementing Google Sign In within my Angular4 app, but I have run into an unusual issue with routing after using router.navigate() in the Google Sign In callback function. To help illustrate this issue, I have created a sample d ...