Updating ng-model with the values from a property in a collection in AngularJS

Encountering an unusual problem with setting the ng-model for a select drop-down menu.

Despite using a property value that matches one in the ng-options, the ng-model consistently ends up as null.

Below is the function responsible for fetching orders:

orderService.getMerchantOrders(qs)
            .then(
            function (response) {
                $scope.isLoading = false;
                $scope.pagerService = new pagerService({
                    page: $scope.pagerService.page,
                    data: response.data.items,
                    total: response.data.total,
                    sortVars: response.data.sort,
                    pageSize: 5
                });
            },
            function (error) {
                if (error.status === 401) {
                    $window.location.href = $scope.returnUrl;
                } else {
                    //show error message
                    console.log(error);
                }
            });

Review of pagerService.data can be seen here: https://i.sstatic.net/WcppO.png

The value of

order.orderShippingMethod[0].shippingMethod
is:

{"shippingMethodId":7,"carrierName":"Russian Post","carrierUrl":"http://www.russianpost.ru/tracking20/English.htm","orderShippingMethod":[]}

The options for the select list are available: https://i.sstatic.net/ENmYs.png

Your input and suggestions are appreciated. As someone new to AngularJs, I believe it's a simple oversight on my part!

<select class="form-control" name="carrierList"

ng-model="order.orderShippingMethod[0].shippingMethod"

ng-options="shippingMethod.shippingMethodId as shippingMethod.carrierName 
for shippingMethod in shippingMethods" required>

<option value="">Select Carrier</option>

</select>

Answer №1

Instead of using id as name, consider utilizing the track by syntax for ngOptions:

shippingMethod.carrierName for shippingMethod in shippingMethods track by shippingMethod.shippingMethodId

Check out the example below:

angular.module('myApp', [])
  .controller('ctrl', function($scope) {
    $scope.shippingMethods = [{
        "shippingMethodId": 7,
        "carrierName": "Russian Post",
        "carrierUrl": "http://www.russianpost.ru/tracking20/English.htm",
        "orderShippingMethod": []
      },
      {
        "shippingMethodId": 8,
        "carrierName": "Persian Post",
        "carrierUrl": "http://www.russianpost.ru/tracking20/English.htm",
        "orderShippingMethod": []
      }
    ];
    $scope.order = {
      orderShippingMethod: [{
        "shippingMethod": {
          "shippingMethodId": 8,
          "carrierName": "Persian Post",
          "carrierUrl": "http://www.russianpost.ru/tracking20/English.htm",
          "orderShippingMethod": []
        }
      }]
    };
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ctrl">
  <select class="form-control" name="carrierList" ng-model="order.orderShippingMethod[0].shippingMethod" ng-options="shippingMethod.carrierName 
for shippingMethod in shippingMethods track by shippingMethod.shippingMethodId" required>

<option value="">Select Carrier</option>

</select> 
<div>
order.orderShippingMethod[0].shippingMethod: {{ order.orderShippingMethod[0].shippingMethod }}</div>
</div>

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

Incorporating Error Management in Controller and Service: A Step-by-Step Guide

Take a look at the structure of my angular application outlined below: Within my 'firm.html' page, there is a button that triggers the code snippet provided. Controller The controller initiates a Service function. The use of generationInProgre ...

UI-Router is failing to transition states when $state.go() is called

I am currently troubleshooting a unit test for my user interface router routes, specifically focusing on the issue I encountered with the test not passing successfully. Within my test script, when checking the value of $state.current.name, it returns &apo ...

Placing error notifications beneath my table rows for a more polished appearance

In the process of creating a review page for my app that showcases uploaded files, I've encountered an issue. Whenever a user uploads files with errors, I want to display a warning message below each specific file. Currently, I'm able to show the ...

JavaScript event manually triggered not propagating within an element contained in an iFrame context

I am currently developing a WYSIWYG designer that enables users to choose colors through [input type="color"] fields. The interface includes inputs on the left side and an iFrame on the right side displaying the generated preview. Normally, when ...

How come I am receiving {"readyState":1} in the DOM instead of JSON data in AngularJS?

Currently, I am facing an issue where instead of the JSON data (which consists of only 49 items) showing up on the DOM, I am getting {"readyState":1}. I believe this is just a test to ensure that my code is functioning correctly. Although I have identifie ...

Try employing an alternative angular controller when working with the bootstrap modal

I am trying to implement a bootstrap modal in my main HTML file, and I need some help on how to call another Angular controller for the modal. The button that triggers the modal is within a div that already has an Angular controller, and this is causing th ...

Guide on Generating SAS Token for Azure Table Storage in a jQuery Application

I am currently working on a jQuery web application that requires read-only access to an Azure Table Storage, fetching one record at a time by passing in the PartitionKey and RowKey. To simplify my code, I have integrated the Azure Storage JavaScript Client ...

Learn how to dynamically disable or hide the "Today" button in an angular-ui datepicker based on whether it is the weekend

What is the process to hide or disable the "Today" button based on a condition, for example, if today is a weekend? The goal is to conceal the "Today" button in such scenarios. <div class="form-group"> <div class="input-group datePicker"> ...

Using PHP to submit a form depending on user selection

Currently, I am working on a basic input form page that includes a submit button. The goal is to have the data from the form written into my MySQL database based on the user's selection. For instance, if the user chooses option X, I want the input da ...

I am attempting to utilize a ref in React to access an element within a MUI modal, but I am encountering issues as the reference to the

I've been encountering an issue while trying to access the component did mount lifecycle method, as it's showing null. Interestingly, when I remove the modal, everything works as expected. However, inside the modal, the ref isn't functioning ...

What is the process for incorporating scripts from SQL Server?

Looking for assistance with integrating a script string from SQL into a client's website using C#. Here is the script from SQL: (function (w, d, u) { var s = d.createElement('script'); s.async = true; s.src = u + &apo ...

What is the best way to retrieve user data and format the output using JavaScript into a structured form?

I am trying to achieve the functionality shown in this image: My goal is to extract user input from a form and display it on my webpage using JavaScript. Below is the code snippet that I have been working on. Code: function show(){ var ...

Update the parameter value in a URL using JavaScript

I have a URL similar to this one here. something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false The parameter I'm interested in is showHiddenElements, and I would ...

What could be causing the issue with res.send not functioning in node js?

I am currently working with node for the backend and angular for the frontend. My issue lies in checking the existence of a file in nodejs and passing the response to angular. Despite my efforts, this process is not functioning correctly. As a novice, I ha ...

Mastering Authentication in React JS: Best Practices

I am currently working on integrating Backend (Express JS) and Frontend (React JS). One of the challenges I am facing is understanding how to manage sessions effectively. When a user logs in using a form built with React JS, the backend responds with a HS ...

What is the best way to incorporate the "child_process" node module into an Angular application?

Trying to execute a shell script in my Angular application has been quite the challenge. I came across the "child process" node library that might be able to help me with this task. However, every attempt to import the library led me to the error message: ...

Encountered an error in Angular1: TypeError - promise.catch does not exist as a

Upon using angular-ui-router, I encountered the following error while clicking on the links view1 and view2 in index.html. The same example worked with the regular angular router. Is there something missing in the code? Thanks. TypeError: promise.catch i ...

Exploring the Potential of Angular's $http Method with Transform Response and

When does caching occur in relation to the application of transformResponse functions in an Angular $http request? Situation: I am working with a REST API that gives back a lot of metadata, most of which is unnecessary for my purposes. As a result, I do n ...

Is it possible for index.html to reference a .js file in an Angular.js 1.x version?

Authorized users are allowed to access the menu items. While User A requires the menu_1.js file, User B does not need it and should not have access to it. I am trying to determine how to include required js files in index.html for an angular.js version 1 ...

The Ajax form's malfunction is attributed to JSON, as it throws a parser error indicating a SyntaxError. Specifically, the JSON.parse function encounters an unexpected end of data at line 1, column 1

I understand that this is a commonly asked question, but I have tried all the solutions provided and none of them have worked for me. My specific issue is that I am unable to load a JSON response from the server using AJAX. Here's the setup: my "scrip ...