Retrieve Chosen Option in AngularJS

One issue I am facing is related to an ng-repeat that displays users in rows. When a user is clicked, it opens a modal popup for editing the user and displays all user details. However, when I select another role for the user and try to retrieve the newly selected row to pass it for http put, it still returns the old text instead of the newly selected item.

// Displaying users in table rows with the ability to edit by clicking on the username

<tr ng-repeat="item in usersData | filter: searchBox">

        <td><a ng-click="openEditUser($index)">{{item.UserName}}</a></td>
        <td>{{item.EMail}}</td>
        <td>{{item.RoleName}}</td>
        <td style="text-align: right;">{{item.IsActive ? 'Yes' : 'No'}}</td>

</tr>

When the modal popup opens, I fetch all the roles from the API and populate them in a <select> field

// Retrieving all roles and populating them in the select field

$http.get('mydomain.com/api/Users/GetAllRole').then(function (response) {
            $rootScope.myData = {};
            $rootScope.myData = response.data;
        });

// Using ng-model="selectedItem.RoleId"

<select ng-required="true" ng-model="selectedItem.RoleId" class="form-control"
                ng-options="item._id as item.RoleName for item in myData">
            <option value="">Select</option>                                


</select>

The problem arises when I change the role for the user in the <select> field. While retrieving $scope.selectedItem.RoleId gives the new selected RoleId, trying to get $scope.selectedItem.RoleName does not reflect the new selection and still returns the previously selected item.

$scope.EditUser = function(){

    $http.put("domain.com/api/Users/UpdateUser", {
       _id: $scope.selectedItem._id,'RoleId': $scope.selectedItem.RoleId, 'EMail': $scope.selectedItem.EMail, RoleName : $scope.selectedItem.RoleName, IsActive: $scope.selectedItem.IsActive

    }).then(function (response) {
        $route.reload();
        $scope.ok();
        $scope.simpleSuccess();
    }, function (error) {
        $scope.ok();
        $scope.simpleError();
    });


  };

Answer №1

It seems that the issue lies in the incorrect ng-model being assigned to your ng-repeat. Currently, the model being used is selectedItem.RoleId.

Angular will only update the RoleId property of your object instead of the entire object. It would be best to set the ng-model to just selectedItem.

<select ng-required="true" ng-model="selectedItem" class="form-control" ng-options="item._id as item.RoleName for item in myData">
    <option value="">Select</option>                                
</select>

Unfortunately, without a JSFiddle provided, it's challenging to confirm if this is indeed the root cause of the problem.

EDIT

If you want the old role to be pre-selected, make sure to assign it to the correct index within the array returned by the API.

You can refer to this JSFiddle I created to see how the ng-select directive should be utilized correctly.

    

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

display the information stored within the sports attribute using React

I am attempting to display the values stored in the sports property. So, I inserted a console log within the sports property. However, an error is being thrown: Syntax error: C:/codebase/src/containers/sports.js: Unexpected token, expec ...

Setting default parameters for TypeScript generics

Let's say I define a function like this: const myFunc = <T, > (data: T) => { return data?.map((d) => ({name: d.name}) } The TypeScript compiler throws an error saying: Property 'name' does not exist on type 'T', whic ...

Utilize Vue.js - Link computed properties with data()

I am currently working on an input field that needs to be either blank or pre-populated based on certain conditions. Condition A: If the user is a new student, the field should be blank Condition B: If the user is an existing student, the field should be ...

The absence of the Three.js file in my HTML file is noticeable

Currently, I am diving into HTML5 and experimenting with the Three.js 3D engine. While following a tutorial from this source, it was recommended that I include the three.js file in my HTML document. However, I encountered two files with the same name and d ...

Only if there is an update in the SQL database, I wish to refresh the div

I have created a voting system and I am facing an issue with the data updating. I have implemented a setInterval function in javascript to load the data every 2 seconds, but it's not working as expected. There are no errors shown, but the data is not ...

Storing the information received from an API as an HTML element

My HTML file contains JavaScript, along with a URL that displays data retrieved from an AWS lambda API call via AWS API Gateway. The page initially appears blank and the data is structured like this: [ {"user": "bob", "groups": ["bobsGroup"], "policies": ...

Is it possible to access all the variables within a specific scope or explore different scopes using console.log?

In the process of writing a graph algorithm, I am currently working on implementing a removeEdge method in the graph prototype. This method takes two arguments, which are the two nodes that will be losing their connection. I have successfully achieved a ...

"Setting an index to a button's ID using Jquery: A step-by-step guide

My goal is to assign incrementing index values to button IDs in a loop. For example, if the first button has an ID of 'unique', the second button should have an ID of 'unique0', and the third button should have an ID of 'unique1&ap ...

Configuring the array interval in an Angular application

I'm facing an issue while attempting to use the setInterval() function to update text for the user every 3 seconds. My attempt at looping with a for loop has not been successful - I only see 'test 03' and nothing else. I'm struggling ...

Please provide pattern block links and any special characters as input

I have a promotion box where users can input text to send to administrators. Objectives I need to prevent users from inputting links and special characters. Users should only be able to input letters a-z (case insensitive) and numbers 0-9. Input is option ...

How can I troubleshoot the issue of not receiving a response while attempting to upload an image using Postman with my Cloudinary-Express API?

Currently developing a backend nodejs/express API to upload image files to Cloudinary, encountering an error during testing with Postman. Below is the backend code: app.post( '/api/upload/:id', asyncHandler(async (req, res) => { try { ...

Unable to log out when the button is clicked

I am having trouble figuring out why I can't log out when clicking the button. I have a logout button in my header (navigation). My experience with React is limited. Within my project folder, I have a Store directory which contains an Auth-context f ...

Retrieve the initial link value in jQuery and make changes to it

Is there a way in jQuery to append to the current value of an attribute without storing it in a variable first? For example: $(document).ready(function() { $("#btn").click(function() { // get the link currently var linkCurrent = $("#link").att ...

Are you interested in monitoring the website's past activity?

Similar Question: How to maintain browser history when utilizing Ajax? I've been trying to find a solution for this issue, but so far I haven't had any luck. Here's the thing: I created a template for my homepage that might not be perfe ...

Tips for configuring your Gruntfile and Yeoman to create a feature-focused layout in your directory

After using Yeoman's angularJS generator (yo angular) to create a new project, the app is set up with a specific directory structure: app scripts controllers aFeatureController bFeatureController directives aFeatureDi ...

How can I display all values in Meteor Blaze by iterating through a mongo cursor?

Can someone please guide me in the right direction? I have an application that uploads a CSV file to MongoDB and then displays it within the Meteor framework. I am facing an issue where I am subscribing to the data in the Template.onCreated function, but I ...

Converting JSON data into XML format

When I am converting JSON Values to XML, instead of getting JSON properties as elements of XML, I am receiving "title":"source". The desired output should be <title>source</title>. Can you help me identify what mistake I mig ...

How can I efficiently create a suffix using this JavaScript code?

Take note that the code displayed below showcases the array in the console, rather than in the snippet output var names = ["maria", "mary", "marks", "michael"]; function add_suffix(names) { var suffixes = []; for (var i = 0; i < names.length; i+ ...

I am currently working on creating a basic task tracker using Express, however, I am encountering difficulties in getting the 'delete' button to function properly

Struggling to implement a simple to do list with a "delete" button that doesn't seem to be working? No errors are popping up, but the button remains unresponsive. Various attempts have been made to fix this issue without success. Uncertain whether the ...

Having trouble with the CSS positioning of divs created with JavaScript: it's not behaving as anticipated

Let me start by saying I have always struggled with CSS positioning. It seems like I am missing something simple here... So, I have a JS script that generates divs within a parent container called #container which is set to absolute position. Here is the ...