The drop-down menu is not visible

Query -

Having an issue with two dropdowns in my view. The second dropdown is dependent on the first one, but for some reason, the second dropdown is not updating as expected.

// First dropdown

  <select ng-controller="myController"
             ng-options="customer.name for customer in customerDetailData"  ng-model="customer"
             ng-change="updateCost(customer)">
                <option value="">Please select customer</option>
    </select>

// Second dropdown

<select ng-controller="myController"
         ng-options="cc.name for cc in customerCostData">
      <option value="">Please select cost</option>
</select>

// Controller

(function() {
    var myController = function($scope,Service){
        $scope.customerDetailData;
        Service.cust()
            .success(function(data){
                console.log(data)
                $scope.customerDetailData = data;
            })
            .error(function(status,error){
            })

        $scope.customerCostData;
        $scope.updateCost=function(customer){
            Service.cost(customer.id)
                .success(function(cost){
                    $scope.customerCostData= cost
                })
                .error(function(status,data){
                    console.log(status);
                    console.log(data);
                })
        }
    };
    myController .$inject = ['$scope','Service'];
    angular.module('app').controller('myController ',myController );
}());

Am I overlooking something? The data is being retrieved successfully in the console. Any guidance would be appreciated.

Answer №1

Here are a couple of important steps to follow:

  1. The primary issue is that the ng-controller is being attached to each select individually. This results in the creation of two separate controllers, one for each select, causing them to have different scopes. To resolve this, you should attach the ng-controller attribute to a parent element, such as the form.

  2. The second issue is that Angular does not automatically update an element simply because the scope variable is used in ng-options. To address this, you need to assign a ng-model so that Angular can properly watch it.

Below is an example of the code with two distinct controller instances. Notice the presence of 2 alerts:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>
    <form ng-app="myApp">
         <select ng-controller="myController"
             ng-options="customer.name for customer in customerDetailData" ng-model="customer"
             ng-change="updateCost(customer)">
            <option value="">Please select customer</option>
        </select>

        <select ng-controller="myController"
            ng-options="cc.name for cc in customerCostData" ng-model="customercustomerCostData">
            <option value="">Please select cost</option>
        </select>
    </form>

    <script type="text/javascript">
        (function () {
            var myApp = angular.module('myApp', []);

            var myController = function ($scope) {
                alert('myController created');
                $scope.customerDetailData = [{ id: 1, name: "bob" }, { id: 2, name: "fred" }];

                
                $scope.updateCost = function (customer) {
                    $scope.customerCostData = [{ name: customer.id.toString() }, { name: 'x' }];
                }
            };
            myController.$inject = ['$scope'];
            myApp.controller('myController', myController);
        }());
    </script>

Now, let's consider the scenario with a single ng-controller applied to the form and ng-model="customerCostData" on the second select, allowing it to function correctly:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>
    <form ng-app="myApp" ng-controller="myController">
         <select
             ng-options="customer.name for customer in customerDetailData" ng-model="customer"
             ng-change="updateCost(customer)">
            <option value="">Please select customer</option>
        </select>

        <select
            ng-options="cc.name for cc in customerCostData" ng-model="customercustomerCostData">
            <option value="">Please select cost</option>
        </select>
    </form>

    <script type="text/javascript">
        (function () {
            var myApp = angular.module('myApp', []);

            var myController = function ($scope) {
                alert('myController created');
                $scope.customerDetailData = [{ id: 1, name: "bob" }, { id: 2, name: "fred" }];

                
                $scope.updateCost = function (customer) {
                    // Simulating an AJAX call
                    $scope.customerCostData = [{ name: customer.id.toString() }, { name: 'x' }];
                }
            };
            myController.$inject = ['$scope'];
            myApp.controller('myController', myController);
        }());
    </script>

Answer №2

Has the cost data been fetched using an Ajax request? If so, you may need to trigger a $digest cycle to update the UI with the new model changes. One way to do this is by wrapping the cost assignment in a $timeout or $apply function.

$timeout(function () {
    $scope.customerCostData = cost;
});

Alternatively,

$scope.$apply(function () {
    $scope.customerCostData = cost;
});

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

A guide on how to insert content into a text area using a drop-down menu choice

I'm a total beginner at this. Is it possible to use JavaScript to automatically fill in a text area on an HTML form based on what is selected in a drop-down menu? If so, can someone please explain how to achieve this? ...

Issue encountered with mouse handling on SVG elements that overlap is not functioning as anticipated

I am working with multiple SVG path elements, each contained within a parent SVG element, structured like this: <svg class="connector" style="position:absolute;left:277.5px;top:65px" position="absolute" pointer-events:"none" version="1.1" xmlns="http:/ ...

Set the default state of an input field to lowercase when using Angular

During our time working with AngularJs, we commonly utilized a default filter that would automatically convert input to lowercase. Unfortunately, this feature does not seem to be supported in Angular+. Can anyone confirm if this information is accurate? ...

Modifying the embed to shift colors over a specified duration in discord.js

case 'test': let time = "10s" const testEmbed = new Discord.RichEmbed() .setTitle("Testing") .setColor('#000000') message.channel.send(testEmbed); setTimeout(function(){ testEmbed.setColo ...

Encountering the Extjs 3.4 error ERR_UNKNOWN_URL_SCHEME while trying to access a legitimate JSON

Using Extjs 3.4, I am working on a simple ajax request: Ext.Ajax.request({ url: "localhost:3000/offers.json", success: function(response, opts) { var obj = Ext.decode(response.responseText); console.dir(obj); }, failure: funct ...

Retrieving blog posts formatted in markdown from a centralized JSON file

My current setup involves using react-markdown to load markdown content from a JSON file. I have opted for a static site hosted on CloudFront to save money and eliminate server operation costs. All posts are compiled into a posts.json file which is then ...

What is the proper way to confirm the authenticity of a captcha code

hey there, I'm struggling with my captcha code. The issue is that it still accepts wrong captchas when entered in the input box. Can someone guide me on how to validate the wrong captcha entry? Here's my form code: <p class="Captcha" style=" ...

Leveraging the power of Javascript/jQuery to manipulate form

On my website, I have implemented a form that requires a customized response for certain zip codes. To achieve this, I am developing a code that validates the first 3 digits of the entered zip code against a predefined array in my system. Although the code ...

Setting a specific index in an array of objects in React: A comprehensive guide

I currently have a useState() object structured as follows: const [financeSummary, setFinanceSummary] = useState({ discountRate: 10, financeRate: 10, reinvestRate: 10, inflationRate: 3, singleInvestment: new Array( ...

Issue: It is necessary to utilize the `@babel/plugin-transform-runtime` plugin if you have set `babelHelpers` to "runtime" when using npm link

My situation involves having two interconnected React libraries: project-ui and propert-utils. project-ui relies on propert-utils, and the latter is installed within the former. "devDependencies": { "@company/project-utils": "gi ...

Troubleshooting Jqgrid Keyboard Navigation Problem

Here is a link to the jsfiddle code snippet. Upon adding jQuery("#grid").jqGrid('sortableRows'); into my JavaScript code, I encountered an issue where keyboard navigation no longer worked after sorting rows Below is the JavaScript code snippet: ...

Avoiding line breaks when submitting data through Ajax calls is achievable by using the `.val` method

I've come across multiple articles discussing ways to add line breaks to the .val in jQuery, but unfortunately none of them have worked for me. I attempted using the recommended workaround provided by jQuery: $.valHooks.textarea = { get: function( ...

Encountered an issue while attempting to retrieve the access token from Azure using JavaScript, as the response data could

Seeking an Access token for my registered application on Azure, I decided to write some code to interact with the REST API. Here is the code snippet: <html> <head> <title>Test</title> <script src="https://ajax.google ...

Utilizing Jquery on the client side in conjunction with a Node.js server

I am using nodejs within a docker-compose container to create a local web app. My goal is to use jquery on the client-side to load an HTML file into a div, but I'm encountering issues with it not working properly. Both the initial index.html and the n ...

Confirm the cell content in the ui-grid

Is there a better way to validate the value of an editable cell in ui grid, such as ensuring that a password field is filled out? Currently, I am using the afterCellEdit event to set the password value back to the old value if it is empty: rowEntity.passw ...

Separating buttons (two buttons switching on and off simultaneously) and displaying the corresponding button based on the data

My current project involves creating a registration page for specific courses. While I am able to display the information correctly, I am facing an issue with the ng-repeat function. The problem lies in all the Register buttons toggling incorrectly. Additi ...

Exploring Node.js: Uncovering the Secrets of Checking Dependency Versions

How can I dynamically retrieve the version of an external dependency in JavaScript without manually specifying it? ...

Angular: handling asynchronous errors when no promise is utilized within a subscription

I am currently working with a material design table and have created custom functions to load the data and extract objects from a JSON array object. Here is a snippet of the code I am using: public getDocumentList() { return this.http.get(this.getDocu ...

Dealing with 401 errors in your entire AngularJS application

One of my Controllers contains the following code to handle a 401 error gracefully: ChannelsService.query(function(response) { $scope.channels = response; }, function(error) { if (error.status == 401) { $state.go('login'); } ...

retrieve the JSON object corresponding to the specific category

Here is an example of a JSON: [ { "id":1, "name": "BMW E46 PANDEM", "price": 130000, "currency":"USD", "color":"white", "category":"car" }, { "id":2, "name": "Yamaha", "price": 2000, "currency":"USD", "c ...