Remove duplicate values from ng-options

Check out this plunker example

I have a collection of cars and their corresponding available years:

  • ["Volvo", "VW", "Audi"] --> [2006, 2007, 2008]
  • ["Ford", "Honda", "Jaguar"] --> [2008, 2009, 2010, 2011]

Note: The year 2008 is duplicated. This is important)

By default, I have assigned the year 2006 (any year besides 2008) for Volvo.
Click "Load car 1", then "Load car 2".
You will observe that 2006 is displayed. It functions correctly.

However, when switching from 2006 to 2008.
Click "Load car 1", then "Load car 2".
2008 disappears. It fails to function properly.

Why is this happening? What am I missing or not comprehending? The value type for SELECT tag doesn't matter (number or string)


If I remove

//I use length = 0 in ng-disabled to prevent user from changing 'year' during timeout interval
if (main.years) main.years.length = 0;

or $timeout, it functions correctly.
Even after trying to use bind, it still didn't work.

Thank you.


Although my example is simple, in my actual project, with numerous fields and a slow client-server system. Furthermore, if I rapidly select cars, the data in cars array and options in the select get lost

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($timeout) {
  var main = this;

  main.selectCar = selectCar;
  main.models = ["Volvo", "VW", "Audi", "Ford", "Honda", "Jaguar"];
  //main.years = [2006, 2007, 2008, 2009, 2010, 2011];
  main.cars = [{
    year: 2006,
    model: "Volvo"
  }, {
    year: 2011,
    model: "Honda"
  }];

  selectCar(main.cars[0]);

  // bind also does not work
  function selectCar(car) {
    // I use length = 0 in ng-disabled to prevent user from changing 'year' during timeout interval
    if (main.years) main.years.length = 0; //will work without this line

    main.activeCar = car;
    getDataFromServer('years');

    console.log(main.cars[0].year);
  }

  function getDataFromServer(nameForOptions) {
    // don't think about this logic
    // $q
    $timeout(function() { //will work without $timeout
      var arr;
      if (nameForOptions === 'years') {
        if (["Volvo", "VW", "Audi"].indexOf(main.activeCar.model) > -1) {
          arr = [2006, 2007, 2008];
        } else {
          arr = [2008, 2009, 2010, 2011];
        };
      }

      main[nameForOptions] = arr;
    }, 100);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<body ng-app="plunker" ng-controller="MainCtrl as main">
  <br /><br />
  <button ng-click="main.selectCar(main.cars[0])">Load car 1</button>
  <button ng-click="main.selectCar(main.cars[1])">Load car 2</button>
  <br /><br />
  <select id="select_1" ng-model="main.activeCar.model" ng-options="model for model in main.models" ng-disabled="!main.models.length"></select>
  <select id="select_2" ng-model="main.activeCar.year" ng-options="year for year in main.years" ng-disabled="!main.years.length"></select>
  <hr />
  <p>Cars:</p>
  <ol>
    <li ng-repeat="car in main.cars">{{car.model}} - {{car.year}}</li>
  </ol>
</body>

Answer ā„–1

You should start by setting the activeCar variable to an empty object. main.activeCar = {};

Answer ā„–2

I accomplished it in this manner plunker fork

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($q, $timeout) {
  var main = this;
  main.selectCar = selectCar;
  
  main.models = ["Volvo", "VW", "Audi", "Ford", "Honda", "Jaguar"];

  main.cars = [
    {
      year: 2006,
      model: "Volvo"
    },
    {
      year: 2011,
      model: "Honda"
    }
  ];
  
  selectCar(main.cars[0]);

  function selectCar(car){
    //I use length = 0 in ng-disabled to user can't change 'year' while timeout interval (wait server response)
    if (main.years) main.years.length = 0;
    
    main.activeCar = {};

    getDataFromServer('years', car).then(function(){
      main.activeCar = car;
      console.log(main.cars);
    });
  }
  
  function getDataFromServer(nameForOptions, car){
    //don't think about this function and logic inside it
    var deferred = $q.defer();

    //wait server response
    $timeout(function(){
      var arr;
      if (nameForOptions === 'years') {
        if (["Volvo", "VW", "Audi"].indexOf(car.model) > -1) {
          arr = [2006, 2007, 2008];
        } else {
          arr = [2008, 2009, 2010, 2011];
        };
      }
      
      main[nameForOptions] = arr;
      
      deferred.resolve();
    }, 100);
    
    return deferred.promise;
  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<body ng-app="plunker" ng-controller="MainCtrl as main">
  <br /><br />
  <button ng-click="main.selectCar(main.cars[0])">Load car 1</button>
  <button ng-click="main.selectCar(main.cars[1])">Load car 2</button>
  <br /><br />
  <select id="select_1" ng-model="main.activeCar.model" ng-options="model for model in main.models" ng-disabled="!main.models.length"></select>
  <select id="select_2" ng-model="main.activeCar.year" ng-options="year for year in main.years" ng-disabled="!main.years.length"></select>
  <hr />
  <p>Cars:</p>
  <ol>
    <li ng-repeat="car in main.cars">{{car.model}} - {{car.year}}</li>
  </ol>
</body>

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

Swap the hyperlink and heading upon clicking

I need to implement a function where a sort bar changes URLs and titles on click. For example, when a link like this is clicked: <a href="http://localhost/11/affiliate/?post_type=affiliate&orderby=title&order=asc ">Title ASC</a> It sh ...

Redux application is not functioning properly

I followed the official documentation to create a Redux app at http://redux.js.org/docs/basics/ but it's not working as expected. I have organized my code into four files: store, reducers, actions, and build. actions.js: export const ADD_TODO = &apo ...

What is the process of invoking a secondary "external" function with Nodejs, Expressjs, and bluebird?

Struggling with creating a nodejs application, a new area for me. I've managed to work with Promises and fetch data from a database. Take a look at the code below: myModel.js var express = require('express'); var app = express(); var Promi ...

There seems to be an issue with the next function's functionality within a Nodejs middleware

Currently, I am delving into the world of Nodejs with expressjs. My focus is on understanding middleware functions and specifically, the role of "next". In the middleware concept, "next" simply moves on to the next middleware in line. So, what exactly is ...

NodeJS video streaming feature does not close the connection when the user disconnects or navigates to a different page

Currently, I'm in the process of developing a video streaming server using nodeJS with express. To monitor the progress status, I am utilizing the "request-progress" module. So far, everything pertaining to video streaming is working perfectly. Howev ...

Is it considered acceptable to invoke an asynchronous function that retrieves initial data within the constructor of a JavaScript class?

Currently, I am working on a sample application using Mobx and Mobx React Lite to gain a better understanding of this state management tool. When a user accesses the page, the app should load questions. I have some doubts regarding whether it is advisable ...

The Angular 2 service is not transmitting the POST data in the correct format, although it functions properly when transmitted through PostMan

When the POST data is transmitted from the Angular 2 service in this manner: const data = new FormData(); data.append('date', '12/01'); data.append('weight', '170'); return this.http.post(this.u ...

Troubleshooting encoding problems with Google Cloud's Speech-to-Text API using Node.js

I'm currently working on a project that involves capturing audio from a user's microphone and sending it to a server for translation using Google's Speech-to-Text API. I am utilizing navigator.mediaDevices.getUserMedia() to access the audio, ...

Is there a way for me to display the output within the component rather than using console log?

I created a simple app.js file in React that continuously checks if a number is prime or not and logs the result in the console every second. Now, I am looking to display this information on my homepage instead of in the console. Any suggestions on how I ...

At what point does Angular's link function execute?

It appears that this script only runs once before the page is displayed. However, is there any scenario in which it runs after the page has been rendered? I decided to experiment with different scenarios using this plnkr: angular .module('app&apos ...

Switch out the URL in npm's build process

While developing, I am using a mock REST service but for the public release, I intend to switch to a real backend. Is there a method to update the endpoint URL during the npm build process? ...

Exploring the flow of resolve promises in UI-router from the main root state to its sub-states

Currently, I am in the process of developing an Angular application with ui-router. The first step I took was to create a root state that serves as an abstract one intended for resolving asynchronous dependencies. This means that any subsequent sub-states ...

Retrieving the chosen option from a dropdown using JavaScript

Feeling completely overwhelmed, Iā€™m struggling to retrieve the selected item from a dynamically created select dropdown list using JavaScript. I have a list of items that represent columns in a table. When I click on an item, I want the corresponding co ...

What is the best way to transfer a variable from a node server to a javascript client when the page is first

My web application is mainly static, but I need to dynamically send the user's username if they are logged in and the room name they specify in the URL to the client-side JavaScript upon page load. Finding a simple solution has been challenging for me ...

Error: Angular2 RC5 | Router unable to find any matching routes

I am currently encountering an issue with my setup using Angular 2 - RC5 and router 3.0.0 RC1. Despite searching for a solution, I have not been able to find one that resolves the problem. Within my component structure, I have a "BasicContentComponent" whi ...

In-Place Editing Revolutionizing Content Editing

What is the most effective method for editing content while using ng-repeat? In an ideal scenario, the added birthday would be displayed as a hyperlink. When clicked, it would reveal an edit form similar to the add form, along with an update button. Chec ...

Encountering a 404 error while attempting to establish a connection between Express and React

My attempt to make a simple API request for bitcoin values is encountering some issues. When I enter in my Chrome browser, I receive a "Cannot Get /" message with a 404 error in the dev tools stating "GET 404 (Not Found)". However, when I visit , I succ ...

What is the best way to set up callbacks for an AngularStrap or Angular UI Bootstrap Popover, to run when the popover is opened and closed?

I am currently exploring the functionalities of the Angular UI Bootstrap popover and I have a particular need to define callback functions for both when it is opened and closed. The purpose behind this requirement is that I intend to utilize the popover fo ...

Modify the colors of <a> elements with JavaScript

I am brand new to the world of UI design. I am encountering an issue with a static HTML page. (Please note that we are not utilizing any JavaScript frameworks in my project. Please provide assistance using pure JavaScript code) What I would like to achie ...

Implementing swipe functionality to Bootstrap carousel

This is the code snippet I am working with: <div class="container"> <div id="myCarousel" class="carousel slide" data-ride="carousel" data-interval="3000"> <!--Indicators--> <ol class="carousel-indicators"> ...