Updating ng-model value in AngularJS controller does does not reflect changes in selection

I'm encountering an issue while trying to upgrade my ng-model within a selection feature.
Here is the HTML code I am currently using:

<div ng-app>
    <div ng-controller="Ctrl">
        <select ng-model="viewmodel.inputDevice"
        ng-options="i.label for i in viewmodel.inputDevices">
        </select>
    </div>
</div>

Below is the JavaScript code I have written:

function Ctrl($scope) {
     // view model
    $scope.viewmodel = new function () {
        var self = this;
        var elem1 = {
            value: '1',
            label: 'input1'
        };

        var elem2 = {
            value: '2',
            label: 'input2'
        }

        self.inputDevices = [elem1, elem2];

        self.inputDevice = {
            value: '1',
            label: 'input1'
        };
    };
}  

You can check out the working example on JSFiddle

My goal is to set the values of inputDevice to match those of the first device in the inputDevices array.
While passing elem1 directly would solve it, I need to store the selection in Local Storage and then restore it to the ng-model object. Any suggestions or tips are highly appreciated!
Thank you

Answer №1

If you want to follow Maxim's example, store the value instead of the object. Alternatively, you can extract the correct value from the inputDevices array using the following method:

self.inputDevice = self.inputDevices.filter(function(item) {
   return item.value == storedValue.value;
})[0];

Refer to this updated fiddle for more information.

Answer №2

The provided code from the original post is functioning correctly for me:

<div ng-app>
  <div ng-controller="Ctrl">
    <select ng-model="viewmodel.inputDevice"
      ng-options="i.label for i in viewmodel.inputDevices">
    </select>

    <!-- This section accurately displays the initial selection and any subsequent choices as : {"value":"1","label":"input1"} -->
    <span>{{viewmodel.inputDevice}}</span>
  </div>
</div>

While your JavaScript code is effective, there are ways to simplify the construction of the view model:

function Ctrl($scope) {
 // Here is the improved view model setup
  $scope.viewmodel = {inputDevices: [
                      {value: '1', label: 'input1'}, 
                      {value: '2', label: 'input2'}
                    ]};
  $scope.viewmodel.inputDevice = $scope.viewmodel.inputDevices[0];

}

Check out this jsfiddle example: http://jsfiddle.net/8t2Ln/39/

Answer №3

Alternatively:

self.inputDevice = {
            value: '1',
            label: 'input1'
        };

I opt to only store the index:

 self.inputDevice = 0; // or 1 for the second item

Additionally:

<select> 
    <option ng-repeat="i in viewmodel.inputDevices" 
            value="{{i.label}}" 
            ng-selected="viewmodel.inputDevices.indexOf(i) == viewmodel.inputDevice"
    >{{i.label}}</option>
</select>  

This method should function correctly.

Improved Example 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

Adjusting div position because of navigation bar elements above

I have implemented Bootstrap to create navigation tabs on my website. Currently, I have two navigation bars within a single div element. While they are functioning correctly, I am facing an issue where toggling through the tabs changes the height of the co ...

Using AngularJS to toggle between two select dropdowns

I have two drop-down lists containing JSON data. <select class="form control" ng-model="fruitsName" ng-options="r.id as r.name for r in fruits"> <option value="">--Select---</option></select> $scope.fruits = [{'id': &apo ...

Form with several file selection points

I am working on an application that features a dynamic form capable of uploading files to different individuals simultaneously. Each person is assigned a unique input file and has the option to add up to 2 additional dynamic inputs. <div id="InputsWra ...

After a prolonged period of running, rendering webgl in requestAnimationFrame was only achieving 1 frame per second

While trying to render a WebGL animation using requestAnimationFrame, I noticed that it runs at 60fps for a period of time before suddenly dropping down to 1 fps. After approximately 500-1000ms, it goes back up to 60 FPS again. I am utilizing three.js to ...

Is it possible to dynamically add an id or class to an element using document.createElement in JavaScript?

As a beginner in the world of JavaScript, I understand that the code structure I have used here may not be ideal for real-world applications. However, I am using it to practice my understanding of for loops and fetching JSON data. My main query is whether ...

Encountering problem with JSON in the bodyParser function

I've encountered an issue while sending data from my React component using the Fetch API and receiving it as JSON on my Express server. When I try to parse the data using the jsonParser method from bodyParser, I only get back an empty object. Strangel ...

How can I define the boundaries for the scrolling of a static background image?

Is there a way to limit how far a fixed background image can scroll down a page? Essentially, is it possible to change the background attachment to static when the bottom of the background image is 10px away from the bottom edge of its div container? In t ...

Utilize modules within the AppModule to promote modularization and maintain separation of concerns in Angular 2

When using templates like those from the ASP.NET Core JavaScript services, typically a single module named AppModule is included. However, in my application, which is divided into two logical areas (AreaA and AreaB), I thought it would be better to use two ...

The program successfully executes its function, however, an error message appears stating: "Error: Cannot alter headers after they have already been sent to the client."

During testing the update post feature in my MERN project, I encountered a strange issue. The post would update successfully, but the page would disappear and I would receive the following error message. However, after restarting the server, the updated po ...

Loading large content using jQuery's .html() method

After experimenting with the jQuery .html() function, I've noticed that it struggles to handle large amounts of text. You can see an example of this issue. Fortunately, a much simpler test case works perfectly fine. While I understand that including ...

Obtaining a data point by referencing a key within a json collection

I am working on an AngularJS function that includes a JSON array like this: $scope.userDetails = [{ name: 'Anil Singh', age: 30 }, { name: 'Reena Singh', age: 25 }]; My goal is to extract all the values of the age key. Here is the co ...

The error message states: "An uncaught TypeError has occurred - the object does not possess the 'jqzoom' method."

I am encountering a browser console error while working on a project involving a magento website. Specifically, I need to implement the jqzoom feature on the product view page. Here's what I have done so far: Added jQuery Included the jqzoom librar ...

Trigger bootstrap dropdown when input is clicked

One of the challenges I'm facing is getting a Bootstrap 4 dropdown to open when a user tabs to it for ADA accessibility. Currently, clicking on the input triggers the dropdown to show, but I need it to work with tabbing as well. Using a focus event a ...

An error has occurred while trying to declare Symbol InputText during an Angular production build

Currently, I am facing an issue while trying to export the primeng modules from a file. During the test build, I do not encounter any errors. However, when I proceed with the production build, I come across the following error: ERROR in Symbol InputText de ...

Looking for assistance with removing hardcoding in HTML and jQuery?

Currently working on a biography page for my company's website that features a grid layout of the employees' profile pictures. Each picture should be clickable, causing the screen to fade to gray and display an overlay with the respective person& ...

AJAX and Python conflict - The requested resource is missing the 'Access-Control-Allow-Origin' header

I am currently developing a unique JavaScript library that has the capability to communicate with a basic Python web server using AJAX. Below is the snippet for the web server class: class WebHandler(http.server.BaseHTTPRequestHandler): def parse_PO ...

Delete the top part of an ArrowHelper in Three.js

Within my code, I have implemented an ArrowHelper and its parameters are updated through the function below (each invocation of this function adjusts the ArrowHelper's dimensions): function updateArrowHelper() { // Update parameters for transpor ...

Converting a text file to JSON in TypeScript

I am currently working with a file that looks like this: id,code,name 1,PRT,Print 2,RFSH,Refresh 3,DEL,Delete My task is to reformat the file as shown below: [ {"id":1,"code":"PRT","name":"Print"}, {" ...

Hot reloading is not functioning properly in webpack-dev-server

We recently made the switch to NodeJS 20 and had to update several components along with it. Our upgrades included moving from vue/cli-service 4 to 5 and from Webpack 4 to 5, resulting in our webpack-dev-server being updated to v4. The issue we are curren ...

Can a function be called from outside its parent function?

I was pondering the possibility of calling a function from outside its parent function: var $element = $( '.element' ); function myFunction( element ) { var width; function onResize() { width = element.width(); } onResi ...