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

Extracting numbers using regular expressions can be tricky especially when dealing with mixed

Currently, I am attempting to create a javascript regex that can extract decimal numbers from a string containing a mix of characters. Here are some examples of the mixed strings: mixed string123,456,00indeed mixed string123,456.00indeed mixed string123,4 ...

TypeScript's type assertions do not result in errors when provided with an incorrect value

We are currently using the msal library and are in the process of converting our javaScript code to TypeScript. In the screenshot below, TypeScript correctly identifies the expected type for cacheLocation, which can be either the string localStorage, the ...

When should ng-repeat be utilized: only when the object type is an array?

I have a detailed object structure below: $scope.document = { "GENERAL_FIELDS": { "Source_Type": "custom", "Annotations": [ "216/content/Factiva_CM_001/Proteins", "216/content/Factiva_CM_001/Fact" ], "Content": [ " ...

Send the cookie with the JSON request

While logged into a secure website with a login, I came across some valuable data that is transmitted through the server in JSON format. By opening Chrome and inspecting the page using the "Network" tab, I discovered a URL utilizing XHR which contained the ...

Having issues with Sequelize and SQLite auto increment functionality. No errors when using AutoIncrement, but the auto increment feature is not working. On the other hand, errors arise when using

I am currently in the process of developing a discord bot, which includes 2 slash commands. One command is called /setup, used for adding the guildId and an adminChannel to a database. The other command is named /onduty, which is used for adding the user, ...

The contenteditable div's selectAll feature doesn't function properly when it gains focus

I'm working with divs in a table structure and here's an example: <div contenteditable="true" onfocus="document.execCommand('selectAll',false,null)">Something</div> Clicking on a div to focus works perfectly, selectin ...

What are some ways to utilize JavaScript for expanding an HTML form?

I am in the process of developing a basic web application that allows users to create messages with attached files. multiple html file inputs using this javascript link: http://img38.imageshack.us/img38/4474/attachments.gif The functionality to "attach a ...

How can I show the total sum of input values in a React.js input box?

Is there a way to dynamically display the sum of values entered in front of my label that updates automatically? For example, you can refer to the image linked below for the desired output Output Image I have initialized the state but I'm struggling ...

Can anyone help me get my carousel to work properly?

I am facing a carousel problem in my personal exercise project. I have gathered HTML, CSS, and JavaScript from the internet and am attempting to integrate them all together. //Sidebar script start $(document).ready(function () { var trigger = $(&apo ...

Enhance Bootstrap typeahead to accommodate multiple values

I have a basic typeahead setup for searching city names. However, upon selecting a city, I also need to retrieve its latitude and longitude in order to send that data to the backend. $('.typeahead').typeahead({ minLength : 3, source : ...

Is there a way to merge the .load function and the document.referrer function together?

Is there a way to load a specific div from the previous page that a user originated from using a form? $(document).ready(function() { $("#div_to_be_populated").load('url #div'); }); How can I utilize the document.referrer function in the ur ...

What are the limitations of using a JS file within an Angular application?

I am struggling to integrate some js methods from a file into an angular application. Unfortunately, the browser is unable to recognize the js file. I have tried following the guidelines in this SO post, but the browser still cannot locate the file in the ...

Leverage Firebase cloud functions to transmit a POST request to a server that is not affiliated with

Is it feasible to utilize a firebase cloud function for sending a post request to a non-Google server? It appears that being on the blaze plan is necessary in order to communicate with non-google servers. Essentially, I aim to perform a POST action to an ...

Be mindful of potential missing dependencies when utilizing event listeners and states within useEffect

Whenever I utilize the addEventListener() method alongside trying to access some state within the useEffect, I consistently face the same issue. Adding the state as a dependency is not an option, as that would result in multiple event listeners being creat ...

emailProtected pre-publish: Running `python build.py && webpack` command

i am currently using scratch-blocks through the Linux terminal I have encountered a problem which involves running the following command: python build.py && webpack [email protected] prepublish: python build.py && webpack Can anyon ...

I'm trying to determine which jQuery event would be more beneficial for my needs - should I go with

I'm facing a dilemma On my website, I need to capture the value of a span within a modal. The value changes when the modal is opened and reverts to the old value when closed. This particular value represents the cart total in my online store. Wheneve ...

Utilizing Javascript to filter data across multiple columns in tables

I've been experimenting with the JavaScript code below to filter table rows. The original code is from w3schools, but I made some modifications to target all input values. It works well for filtering one column, however, when I try to input a value in ...

Customize the background color of highlighted text using HTML and jQuery

Recently, I modified an existing code to divide plain text into four classes by selecting a portion of the text and coloring it. Afterwards, I extracted the text of each class and stored it in my database. While this code works well, I am looking for a way ...

Using Angular $resource to store an object with arrays

Consider a scenario where we have a User $resource structured as follows: $scope.user = { name: 'John', hobbies: [1, 2, 3] } If we were to save User.save($scope.user) to the server, it would send the following parameters: name: 'John& ...

Display the name of the file on the screen

Is there a way to dynamically display the file name in a view instead of hardcoding it? I would appreciate any assistance. Thank you! Here is my code snippet: <li> @if (Model.Picture2 != null) { base2 = Convert.ToBase64String(Model.Pict ...