Maintaining selected options in select lists while updating model data in Angular

New to Angular and exploring the Product object with Sku objects nested inside.

An app allows users to fetch a product, resulting in the Product object being assigned to $scope.product:

var app = angular.module('app', []);

app.controller('AppController', ['$scope', '$http', function($scope, $http){

    $scope.product;

    //selected sku model from dropdown
    $scope.selectedSku;

    /*
    * Fetch product data from server
    */
    $scope.getProduct = function(){
            $http.post('get_product', {product_id: $scope.extProductId}).
            success(function(product){
                    $scope.product = product;
            }).
            error(function(data){
                    console.log('something went wrong');
            });
    };

In addition to $scope.selectedSku, there's a select list showing Sku options:

<select class="form-control input-lg" ng-model="selectedSku" ng-options="sku.sku for sku in product.skus">
    <option value=""> -- Select SKU -- </option>
</select>

During user interaction, re-fetching the Product object results in the select list reverting to "-- Select SKU --". Is this due to the new Product object replacing the underlying data?

How can Angular maintain the connection to selectedSku when re-fetching the Product?

Should I store the ID of the selected SKU and re-select it programmatically after the Product is re-fetched?

The Product object structure with Sku objects is as follows:

{
    id: 1,
    name: "Product Name",
    skus: [
        {
            id: 1,
            name: "Sku 1 Name",
        },
        {
            id: 2,
            name: "Sku 2 Name"
        }
    ]
}

Answer №1

If you are open to sacrificing the entire object in the model, you can implement a solution like this using ng-repeat instead of ng-options.

<div ng-controller="AppController">
    <select class="form-control input-lg" ng-model="selectedSku" >
        <option value=""> -- Select SKU -- </option>
        <option ng-repeat="sku in product.skus" ng-selected="{{ sku.id == selectedSku }}" ng-value="sku.id" ng-bind="sku.id"></option>
    </select>
    <button ng-click="resetProductSkus()">Reset Product Skus</button>
</div>

The JavaScript code:

var app = angular.module('app', []);

app.controller('AppController', function ($scope, $http) {

    $scope.product = {
        skus: [{id:1},{id:2},{id:3},{id:4}]
    };

    $scope.resetProductSkus = function() {
        console.log('resetting products');
        $scope.product = angular.copy($scope.product);
    };
});

http://jsfiddle.net/nobsex5t/26/

Answer №2

Locate the desired product within the $scope.product.skus using its ID, and perform the following action: $scope.product = selectedProduct ;

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

Setting the value for datepicker and timepicker in ReactJS for individual rows

Can you please explain how to set a default value for the datepicker and timepicker in each row? I have successfully implemented the datepicker and timepicker functionalities in my code. In the home.js file, there is a state called additionalFields which ...

Leveraging CasperJS in a typical JavaScript script

I am currently working on a NodeJS project that involves integrating CasperJS. However, I have encountered an issue where the 'casper' module cannot be located. In an attempt to resolve this, I decided to npm install spooky --save based on some s ...

Executing the slideToggle() function in JQuery with javascript

Trying to create a script that expands and collapses when users click on either the text or image. The image is a basic arrow that switches to an arrow pointing upwards when the div is expanded. The issue I'm facing is that the text disappears when t ...

Displaying elements above my React sidebar

I am working on developing a Login application with a landing page using React Router and Redux. In order to have a Sidebar that is always present in all the components within the application, I have setup the Sidebar component as a route that is constantl ...

Tips for sending data from an HTML page to an Angular custom element

I have successfully created an angular custom element from an angular component that I would like to call from a standard HTML page. The custom element requires a parameter, which functions properly when called as a component within an angular project. Ho ...

The IE9 confirmation dialog fails to pause for user response, resulting in automatic postback before user input is received

Behind the Scenes btnNext.Attributes.Add("onclick", " return Verification(this,'" + GetLocalResourceObject("message").ToString() + "'); ") .ASPX Page [Within javascript tags] function Verification(source, message) { var dialog = '< ...

What are the benefits of removing event listeners in Reactjs?

In my opinion, the event listeners need to be reliable and consistent. React.useEffect(() => { const height = window.addEventListener("resize", () => { setWindowSize(window.innerHeight); }); return () => window.remov ...

Make sure to validate for null values when extracting data using the useSelector hook

Could someone help me with checking for null while destructuring data? const { vehicles: { data: { reminderVehicles }, }, } = useSelector((state) => state); The code snippet above is throwing an error message: Attempting to ...

"Executing the command 'npm run dev' is successful, however, the command 'next dev' does not yield the expected result

Trying out Next for the first time using npx create-next-app, but running into issues with the scripts. While npm run dev works without any problems, executing next dev gives me an error saying zsh: command not found: next. Any idea why this is happening? ...

How can a tab be created using a link within a tab using jquery easyui?

Tabs documentation My goal is to add a new tab from a link within an existing tab. For instance, in tab A, there should be a link "open tab B" that when clicked, adds tab B. I have attempted to create a tab with a link outside of the tab (which works). ...

What is the preferred workflow for client-side modules: (Browserify + npm + gulp) or (RequireJS + Bower + gulp)?

As I delve into various client-side Javascript modules workflows for my current Node.JS Express project, I find myself torn between Browserify + npm + gulp and RequireJS + Bower + gulp. While I lean towards CommonJS due to its syntax, the idea of sharing ...

How do I use React and Material-UI to efficiently display multiple tables from a complex JSON object containing multiple arrays of data?

Trying to come up with an innovative approach to generate a unique dynamic table component that can create individual tables based on the number of arrays in a dictionary object (essentially iterating through each array and generating a table). For my sce ...

ng-view does not support ng-repeat rendering

I have a basic app using ng-view and ng-repeat. Initially, it worked fine without ng-view, but after switching to ng-view, the ng-repeat stopped functioning correctly. Oddly, when I clicked on the "menu" link, it displayed another set of $var instead of ch ...

Passport verification complete but fails to redirect, displaying a 500 error instead

Currently, I am deepening my understanding of the mean stack through the development of a social media web application similar to Twitter. However, during the signup or login process, everything seems to be working smoothly as the user is successfully crea ...

What sets Firebase apart from Express in terms of its core functionalities?

Currently, I am delving into the realm of writing an API using Express and MongoDB while incorporating Angular for routes and views. I have been contemplating whether Firebase and AngularFire could potentially eliminate the need for Express altogether, mak ...

Calculate the total rows within a specified date range

Within my database, there is a column named IsStaff, which returns a value as a bit. This signifies whether a staff member in a company has an illness (1) or not (0). How can I construct an SQL query to count the occurrences of both 1's and 0's w ...

What is the best method for converting input files into FormData?

I recently created a form that allows users to upload both an audio file and an image file simultaneously. However, during testing, I noticed that the alert only displays basic data and does not include the form data. function PodcastUpload({ data }) { ...

How can one easily retrieve the callback function arguments from outside the function?

Here is a snippet of my code: var jenkins = require('jenkins')('http://192.168.1.5:8080'); var job_name = undefined; jenkins.job.list(function doneGetting(err, list) { if (err) throw err; job_name = list[0].name; }); jenkins. ...

Unable to execute tests on angular example project

I recently cloned the Angular Material-Start project. According to the documentation: When I run npm run tests to start all my Karma unit tests, I encounter an error: npm ERR! Windows_NT 10.0.10586 npm ERR! argv "C:\\DevSoft\\Node ...

How can one smoothly rewind X frames in a video or animation on a webpage without experiencing lag?

For my thesis presentation, I decided to make it available online as a video with custom controls resembling a powerpoint slideshow. The challenge I encountered was with transitions between slides in an animated video. Certain transitions needed to loop fo ...