A method to link the chosen state of an option to a boolean variable in AngularJS

My task involves managing a collection of select elements with options specified in a JSON object. Each option should have its selected state preserved as a boolean value. This means that when a user chooses an option, the "selected" value for that option should change to "true", while any previously selected option will have its value changed to "false".

<div ng-repeat="choice in choices">
            {{choice.name}}:
            <select>
                <option value="" ></option>
                <option ng-repeat="option in choice.options" ng-selected="option.selected">{{option.name}}</option>
            </select>
        </div>

Here is an example of how an option would be structured:

{id=1, name='option1', selected=false}

Answer №1

If you want to simplify things, consider restructuring your model in this way:

HTML

<select ng-model="selectedChoice" 
ng-options="opt as opt for (opt, obj) in options">
    <option value=""></option>
</select>

Controller

$scope.options = {
    "option1":{
        id:1, 
        name:'option1', 
        selected:false
    },
    "option2":{
        id:2, 
        name:'option2', 
        selected:false
    },
    "option3":{
        id:3, 
        name:'option3', 
        selected:false
    }
}

$scope.$watch("selectedChoice",function(newVal, oldVal){
    if(!newVal) return;
    $scope.options[newVal].selected = true;
    $scope.options[oldVal].selected = false;
});

Fiddle

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

Creating an asynchronous function using async/await and assigning it to a variable in JavaScript

I am new to javascript async await functions and recently encountered an issue with asynchronous requests in my backend. I tried to initialize the result of the request in a variable, but instead of getting the value, I received a promise when logging the ...

How to Use Angular 8 to Filter an Array of Objects Based on Numeric Values

Can the list be filtered based on the value of iseidaCcaa.id? var centers = [ { id: 2, nombre: "Centro 2", iseidaCcaa: { id: 1, }, }, { id: 3, nombre: "Centro 3", iseidaCcaa: { id: 1, }, }, { id: 1 ...

Axios sending a 400 Bad Request to Django due to a missing required field

I'm having issues sending a POST request from my React frontend using Axios. import axios from 'axios' axios.post('http://server:port/auth/login', { username: 'admin', password: 'MY_PASSWORD', }, { ...

What is the best way to avoid the @ symbol when retrieving JSON data in AngularJS?

I am currently attempting to retrieve data from a JSON file using Angular. The structure of the JSON is as follows: { "@rid":"#12:0", "@version":2, "@class":"Node", "name":"1", "childs":[ { "@rid":"#11:2", "@version" ...

Developing a TypeScript NodeJS module

I've been working on creating a Node module using TypeScript, and here is my progress so far: MysqlMapper.ts export class MysqlMapper{ private _config: Mysql.IConnectionConfig; private openConnection(): Mysql.IConnection{ ... } ...

Making a div element within another div element

<div class="outer"> <ul> <li> list one </li> <li> list two </li> <li> list three </li> <li> list four </li> ...

Solution for adjusting line width on Windows in Three.js

I'm currently working on creating a dynamic 3D coordinate system using the Three.js library. My goal is to add some thickness to the axes, which I've been able to achieve by adjusting the LineBasicMaterial's linewidth parameter. The code sn ...

What is the solution to determining the accurate span form value?

The script below calculates a simple sum, displaying an error if the sum exceeds or falls below 100. Despite the error message, the user can still proceed to the next page. I want to restrict the user from moving to the next page until the sum equals 100 ...

What could be causing this Facebook javascript-sdk login code to repeatedly log in the user automatically?

After pressing the logout button on my site, I am still unable to keep a user logged out. Although they are redirected to the login page, the updateButton function is called again with the same credentials causing them to be logged back in. Despite trying ...

What are some javascript libraries that can be used to develop a mobile image gallery for both Android and iPhone

I currently have the touch gallery system in place, but unfortunately it isn't functioning properly on Android devices. ...

The Query object is not defined in the Express framework

When the postData object is received in the controller as a query, and I log the object, it contains the following data: console.log("data:- ", req.query.postData); The console output is: data:- { "property1":"value1" ...

World space-based UV displacement in GLSL fragment shader

I need some help creating an rgb offset effect for images on my website. I've managed to get the basic functionality working, but I'm facing an issue where the channels are offset based on the uv of the texture. This means that if the images have ...

NodeJs error: the response status function is missing

Encountering the error message "res.status is not a function" while working with this route. Any suggestions on how to resolve this issue? Thank you! exerciseRouter.post('/update/:id', (res, req) => { Exercise.findById(req.id) .th ...

Exploring nested elements in MongoDB with the help of Node.js API

In my current Node.JS API, I have a function written like this: Board.find({ users : req.user._id}) This function is designed to find all documents where the user's id is inside the array named users. For example, it will successfully fin ...

Mastering state management for various input types in React

Developing a proof of concept for showcasing tennis player details on a webpage. The page can display information for any number of players, and the user should be able to update all player details simultaneously. I have created 3 components: PlayersPage, ...

What is the method for automatically verifying elements within nested ng-repeats?

My div contains ng-repeat elements that are interconnected. Each ng-repeat element has checkboxes, and I want to automatically check the related elements in other ng-repeats when a top ng-repeat element is checked. Here is the actual representation of the ...

"Utilize Angular to inject a module into several different modules simultaneously

I'm trying to load a module called userFromServer on my base html page. My goal is to inject it into both the main app module and the mixpanel module. However, I'm encountering an injection error when I attempt to inject userFromServer into analy ...

Tips for setting the active tab in AngularJS with validation included

When I created two tabs, I encountered an issue where clicking the submit button would only validate the first tab and not automatically switch to the second tab. How can I solve this problem? Thank you in advance for your help. angular.module('myA ...

I am facing an issue with my React JS component where it is only able to update the first time I click on a row in

I am encountering an issue with my list where the detail view is not updating when I click on a new row. This is happening after the first click, and as a beginner, I am unsure of how to resolve this. My detail component, named "UpdateSupp," contains the f ...

The proper method of updating the scope value within an AngularJS view

Click here to see the code <a ng-click="deleteOrdersUpdate()">Update</a> <span class="red">{{noOfOrders}}</span> This is the controller code $scope.deleteOrdersUpdate=function () { $scope.noOfOrders=$scope.selection.length; ...