What is the process for defining the value in a select query?

http://jsfiddle.net/WcJbu/

I would like the favoriteThing selector to update with the current selection when choosing a person.

<div ng-controller='MyController'>
    <select ng-model='data.selectedPerson' ng-options='person.name for person in data.people'></select>

    <span ...> likes </span>

    <select ... ng-model='data.favoriteThing' ng-options='thing.name for thing in data.things'></select>
</div>

$scope.data.people = [{
name: 'Tom',
id: 1,
favorite_thing_id: 1
}, {
name: 'Jill',
id: 2,
favorite_thing_id: 3
}];

$scope.data.things = [{
name: 'Snails',
id: 1
}, {
name: 'Puppies',
id: 2
}, {
name: 'Flowers',
id: 3
}];

Should I establish a service and incorporate watches, or is there a better method to utilize the favorite_thing_id directly in the select?

Answer №1

Modify the second dropdown to be like this:

<select ng-show='data.selectedPerson' ng-model='data.selectedPerson.favorite_thing_id' 
        ng-options='thing.id as thing.name for thing in data.things'></select>

By including thing.id as in the ng-options, you can now select entries from data.things based on their ids instead of references. Changing the ng-model to

data.selectedPerson.favorite_thing_id
will prompt angular to automatically switch to the correct option according to selectedPerson.favorite_thing_id.

jsfiddle: http://jsfiddle.net/bmleite/4Qf63/

Answer №2

http://jsfiddle.net/4Qf63/2/ meets my requirements, but I find it somewhat lacking.

$scope.$watch(function() {
    return $scope.data.selectedPerson;
}, function(newValue) {
    if (newValue) {
        $scope.data.thing = $filter('filter')($scope.data.things, {id: newValue.favorite_thing_id})[0];
    }
})

I wish there was a way to achieve all of this directly within the select statement. Perhaps I will attempt to create a custom directive. association = {key: matchValue} This would enable me to do

<select ... ng-model='data.thing' ng-options='t.name for t in data.things' association='{id: "data.selectedPerson.favorite_thing_id"}'></select>

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

Using Angular 2+ to make HTTP POST requests and interact with the GDrive API. Implementing resumable file uploads

I am currently facing a challenge with uploading files to Google Drive using Angular 2. I have managed to upload files successfully, but they end up being labeled as "Untitled" without any title. Below is the code snippet I am using for the upload process ...

Encountering a TypeError when using the react useRef() hook

During my work on an app utilizing the webRTC API and working with the useRef() hook in React, I encountered an error Error: TypeError: myVideo.current is undefined ContextProvider SocketContext.js:27 promise callback*ContextProvider/< SocketCon ...

I am having trouble with cookies, as I am unable to retrieve them from my localhost server

Currently, I am in the process of developing a user validation system for my application. However, I have encountered an issue with validating a token as it appears that the necessary cookie is not being retrieved from my browser's storage. Strangely, ...

Mysterious symbols appearing in text/html encoding on Firefox

When I retrieve a text/html content from a ".txt" file using jquery.ajax(), everything works fine in other browsers except for Firefox. In Firefox, I see strange characters like ... This is my code: $.ajax({ url: "menuProcesso.txt", ...

Creating a Wireframe in Three.js Using a RawShaderMaterial with LineSegments

In the midst of my work on a project, I encountered a dilemma with rendering an intricate wireframe using THREE.LineSegments. My objective is to gradually animate the vertices within this LineSegments material (referred to as warehouse in the project), but ...

Incorporate the teachings of removing the nullable object key when its value is anything but 'true'

When working with Angular, I have encountered a scenario where my interface includes a nullable boolean property. However, as a developer and maintainer of the system, I know that this property only serves a purpose when it is set to 'true'. Henc ...

The function being called within useEffect is rendering too quickly, causing it to break. However, it functions correctly after

When using React-id-swiper to load images for products, I encountered an issue with setting the useState 'loading' state to false after all images have been successfully loaded. In this case, there are 5 products. To achieve this, I implemented ...

Using Rails' link_to method within Bootstrap modals

I'm trying to implement a voting system where users can vote on different items displayed in a Bootstrap modal. Each item is listed as a button on the index page, and when clicked, it opens up the modal for voting. However, I'm facing challenges ...

What is causing jQuery to report an "invalid assignment on the left-hand side"?

function updateAuditor(aud) { jQuery("#auditing").val() = aud; jQuery("#auditTrailForm").submit(); } What causes the error when I attempt to assign 'aud' to the value of #auditing? ...

Utilize NodeJS to dynamically alter the text outputted on an HTML page

For educational purposes, I am designing a website where users can sign in by entering their name on the login page. After signing in, they will be redirected to the home page which displays a personalized welcome message using their name. I have included ...

Clear Vuex state upon page refresh

In my mutation, I am updating the state as follows: try { const response = await axios.put('http://localhost:3000/api/mobile/v3/expense/vouchers/form_refresh', sendForm, { headers: { Accept: 'application/json', 'C ...

Establishing a proxy server to support the development of a Create React application

Recently, I initiated a react application with the help of create-react-app. Following that, I executed the npm run eject script to unlock access to all files. Subsequently, I incorporated express and crafted a server.js file which is located on the same l ...

Presence detected: Discord bot appears online but is missing from members list

I am embarking on the journey of creating my first Discord bot. After installing NodeJS on my computer, I used the Discord developer tools to create the app, turned it into a bot, obtained the token, selected privileges, and added the bot to my server. I ...

Ways to resolve cross-domain problems without the utilization of PHP

I have successfully implemented the code below, however I used demo.php to address the cross domain issue. How can I achieve this without using PHP, as the client prefers not to use it? $('#basic-search').submit(function(el){ var sear ...

Use jQuery to collapse all of the child elements that are currently expanded under a specific parent element

In my list order, I have multiple levels nested within each other: <ul> <li>level 1 a <ul> <li>level 2 a <ul> <li>level 3 a</li> < ...

Swap out a paragraph with a city name fetched from a JSON file

While working on a weather app, I encountered an issue. The app needs to automatically detect the user's location and display the appropriate temperature along with the city name. I have been trying to fetch data from JSON to replace the placeholder t ...

Unusual behavior observed in the angular-daterangepicker module

I'm currently working on an Angularjs application and utilizing the angular-daterangepicker to input dates into a table. Upon the initial load of the app, the startDate is automatically set to the current day and the endDate is set to 4 days later. T ...

Establish a connection to AWS by utilizing MQTT.js

Looking to create a web page that connects to an AWS server? While python-Paho-mqtt allows for the use of tls_set to add security certificates and more, how can we achieve the same with MQTT.js? And if unable to do so, what are the steps to run python-PAHO ...

Activate the Alert (https://material-ui.com/components/alert/#alert) starting from the React component at the bottom of the hierarchy

When it comes to alerts, a normal alert is typically used like alert("message to be displayed");. However, I prefer using material UI Alerts which return a JSX component. For example: <Alert severity="success">This is a success alert — check it out ...

Not prepped for EasyFB

Currently incorporating Easy Facebook for AngularJS (https://github.com/pc035860/angular-easyfb) into my project and encountering some inconsistencies in its functionality. Upon inspecting with console.log(ezfb);, I discovered the following: https://i.sta ...