Issue with the binding of ng-options in AngularJS is unresolved

I'm encountering difficulties trying to update a select element in the view when changes occur in the model. In my implementation, I am utilizing ng-options as shown below.

<select ng-options="item as item.empName for item in employees track by item.ID" ng-model="emp.selected">

To demonstrate the problem, here is the simplest scenario I could create.

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

$scope.employees = [
   {
    "empName": "John",
    "ID": 1
   },
];

setTimeout(function(){ 
    $scope.employees = [
       {
        "empName": "John",
        "ID": 1
       },
       {
        "empName": "Sam",
        "ID": 1
       },
       {
        "empName": "Frank",
        "ID": 1
       }];
    }, 100);


}]);

The select element displays only 'John' and fails to reflect the additional names that are added later. Even using $scope.$apply(); does not resolve the issue.

Answer №1

Make sure to utilize $timeout instead of setTimeout

Answer №2

It's possible that the problem lies with ngModal, so try adjusting the ngModel value and see if that resolves it.

Answer №3

I have modified the code to include a watch on the model for updating purposes. Make sure to update the IDs as you are tracking them with ID.

angular.module('myApp', []).controller('InputCtrl', ['$scope', '$timeout', function($scope, $timeout) {
        $scope.employees = [{
            "empName": "John",
            "ID": 1
        }, ];
 // watch on employees model, so that you get updated value.
        $scope.$watch("employees", function(newv, old, scope) {
            $scope.employees = newv;
            console.log(newv)
        }, true);

        $timeout(function() {
            $scope.employees = [{
                "empName": "John",
                "ID": 1
            }, {
                "empName": "Sam",
                "ID": 2
            }, {
                "empName": "Frank",
                "ID": 3
            }];
        }, 100);


    }]);

To verify in your html, add Name :{{emp.selected.empName}}

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

Modify div content based on user selection

I have a question about updating the content of a div based on certain conditions in my code. Here is what I'm trying to achieve: <div class="form-control" ns-show="runningImport" disabled="disabled"> {{input[row.header_safe]}}{{select[row. ...

Error: Unable to locate module: Material-UI - Please check the path and try again

Encountering this error: Error message: Failed to compile ./node_modules/@material-ui/core/Modal/Modal.js Module not found: Can't resolve '@babel/runtime/helpers/builtin/assertThisInitialized' in 'C:\Users\rifat\ ...

Choose a list in order to create a new list

If I were to choose a specific state in Nigeria, what steps should I follow to generate a drop-down menu with a list of local governments within that state? ...

What is the best way to verify if an XMLHttpRequest made to my public API originates from my own web application or from a third-party client in order to maintain priority?

Is there a method to determine on the API side whether a XMLHttpRequest is coming from my own web application (i.e. the JavaScript I developed) or from a third-party application? The issue appears to be that since the JavaScript runs on the client side an ...

How can one extract dates from a range using mongoose?

Currently, I am working on a rental app project. One of the key functionalities I am trying to implement is the ability to determine the availability of cars between two specified dates, including those dates themselves. Within the database, I have two mai ...

Filtering and selecting tables in HTML

I am dealing with an HTML table that combines static data and MySQL input. The filtering functionality is working properly, but I am struggling to add the options "yes" and "no" to the selection list. These values are test inputs fetched from MySQL. I need ...

Utilizing Cpanel to trigger the loading of PHP content upon button click

I have designed a custom template for a cpanel business website. I am looking to implement functionality where clicking the "Add product" button loads another PHP file into the gray area on the page. This gray area is represented by a div element. Is there ...

How can I automate the process of clicking each button on a page one by one simultaneously?

I'm looking for a way to add a small delay of 1 second after each button is clicked in my code. I want the buttons to be clicked one after the other, not all at once. How can I achieve this until all buttons are clicked? Below is the current code: v ...

Understanding JavaScript Regular Expressions

To ensure that no HTML tags are entered into a textarea, I am utilizing the following regex for validation. If any HTML tags are detected in the textarea, I need to display a validation message. The regex being used is: /<(\w+)((?:\s+\w ...

Prevent the border from shrinking upon being clicked

I'm currently working on customizing an accordion using jQuery for the animation effects. However, I am facing an issue where clicking on the accordion header causes the border around the plus sign to shrink in size as well. My goal is to only have th ...

Storing a variable in Vue on one page and accessing it on another page

Is there a way to transfer a value from config.js file to Geturl.vue? The content of the config.js file is as follows: var myUrl = "http://localhost:7070/#/"; The code snippet in my view file (Geturl.vue) is shown below: <div id="app>> <p ...

Dealing with asynchronous requests in server-side node applications

Currently, I am in the process of constructing a basic node service that carries out the following functionalities: Handles incoming GET requests from web clients Parses the parameters provided Utilizes these parameters to asynchronously query another RE ...

Developing perforations in three.js

This excerpt was sourced from a discussion on adding holes to rendered shapes in Three.js, as seen at THREEJS: add hole to rendered Shape. Despite trying the provided code, it is still not functioning as expected. The encountered error message reads: t ...

Using a nested ng-repeat with an ng-if condition to exclude the nested array

My JSON array includes... { "Name" : "ABC", "rating": [ { "id": null, "Percentage": 40 }, { "id": 0, "Percentage": 40 }, { "id": 1, "Percentage": 20 } ], "email" : "<a href="/cdn-cgi/l ...

Struggling with retrieving information from a basic JSON file using React

I am facing an issue where I need to retrieve data from a local JSON file. The following is the code snippet I am using: const myReq = new Request('./data.json') fetch(myReq) .then(rawD=> rawD.json()) .then(inf ...

The ScrollToTop feature in MUI component seems to be malfunctioning when paired with the useScrollTrigger hook

I am in the process of developing a custom ScrollToTop component using MUI's useScrollTrigger hook. More information can be found at this link Feel free to check out the sample code here: https://codesandbox.io/s/stackoverlow-mui-usescrolltrigger-er9 ...

Incorporating data sets from an already established highcharts chart

I created a chart using highcharts and I am looking to update it, but I am struggling with this particular line of code that is adding random data instead of the data I want to use from JavaScript. // Add the new series. chart.addSeries({ data: Highcharts ...

Using Jquery to create a fading effect when changing the color by checking a checkbox

I'm struggling with adding a fading effect to change the background color of the body element when a checkbox is checked. The color changes successfully, but I can't figure out how to make it fade smoothly. Here is the HTML code: <div class=& ...

Is submitting with JQuery always a hit or miss?

Hey there, I'm currently working on a problem and could use some help. I seem to be having trouble getting inside my function for form submission in JQuery. Despite setting up console.logs, it appears that my code never reaches the first function. Can ...

What is the best way to display the key within an object in a mui-datatable?

I attempted to define it in the following manner: { name: "colorList", label: "Color", options: { filter: true, sort: true, customBodyRender: (value, tableMeta, updateValue) => { ...