assigning a value of undefined to the selected option in AngularJS

How can I use angularjs ng-options and ng-model directives to set the select option and detect when the dropdown option is selected or changed? I want to include an extra empty option so that the user can deselect it, and in that case, I want the value in the ng-model expression to be undefined. Is there a way to achieve this without removing the empty option entirely?

In this Plunker example, I intend for the data.model to be undefined when the empty option is selected, but it currently shows as null instead.

https://plnkr.co/edit/d9Jzs4YgqpWHbOxonwa3?p=preview

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-select-ngvalue-production</title>


  <script src="//code.angularjs.org/snapshot/angular.min.js"></script>
  <script src="app.js"></script>

    </head>
    <body ng-app="ngvalueSelect">
      <div ng-controller="ExampleController">
      <form name="myForm">
        <label for="ngvalueselect"> ngvalue select: </label>
        <select size="6" name="ngvalueselect" ng-model="data.model" multiple>

          <option label='' value="{{undefined}}"/>
          <option ng-repeat="option in data.availableOptions" ng-value="option.value">{{option.name}}</option>

        </select>
      </form>
      <hr>
      <pre>model = {{data.model === undefined | json}}</pre><br/>
    </div>
    </body>
    </html>

The corresponding app.js code is as follows:

(function(angular) {
  'use strict';
angular.module('ngvalueSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     model: null,
     availableOptions: [
          {value: 'myString', name: 'string'},
          {value: 1, name: 'integer'},
          {value: true, name: 'boolean'},
          {value: null, name: 'null'},
          {value: {prop: 'value'}, name: 'object'},
          {value: ['a'], name: 'array'}
     ]
    };
 }]);
})(window.angular);

Thank you!

Answer №1

Two key issues have been identified in the code:

  1. The dropdown menu allows for multiple selections due to the presence of the multiple attribute. As a result, the model stores an array of selections. The desired value is one of the elements within this array, however, the comparison in the code is between undefined and the entire array.
  2. The additional option should utilize the ng-value attribute instead of
    value</code. It is not necessary to create a separate option; the option can be added directly to the <code>availableOptions
    object (e.g., {value: undefined, name: ''}).

For the updated code, please visit the following plunker link: https://plnkr.co/edit/RXUlW6P7DX2wPZOazwe8?p=preview

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

Connecting Vue.JS page to my existing HTML page: A step-by-step guide

While developing my website, I faced a challenge with the structure. The home page was built using traditional HTML/CSS, while the other pages were created in Vue.js. Is there a method to connect these two different types of files? For instance, can I inc ...

Encountering a syntax error with JSON.parse() when using MVC 4 Razor with Jquery Ajax

I am encountering an issue with my MVC 4 application login page. I am attempting to utilize a jQuery ajax request to my login controller to check if the user exists. Here is the snippet of my jQuery code: $(document).ready(function () { $("#btnSub ...

Issue with Angular 2 - Struggling with Routing

My objective is to create a menu with four links, each leading to a different HTML page: <p> <a routerLink="/function">Business Function</a> <a routerLink="/process">Business Process</a> <a routerLink="/appsystem"> ...

Navigating through elements in an array in node.js

Within my array, I store the languages that users prefer. Here is an example: let language = [] var Lang = "it" language.push(Lang) This process is repeated with various languages. The array would eventually contain these values: language ...

Instructions on removing an HTML element from a div that has the attribute contentEditable

Here is an example of HTML code: <div id="editable" contentEditable="true"> <span contentEditable="false">Text to remove</span> </div> I want to be able to delete the entire span element (along with its text) with just one bac ...

Determining whether the user has a token stored in the localStorage is a crucial step in my

I have an app that calls a Login API and returns a token. I store the token in localStorage, but I'm unsure how to validate if the user has a token to log in. What steps can I take to solve this? Below is my login page where I store the token in loca ...

The slider components have an endless loop feature that only runs once before coming to a

I'm working on creating an infinite slider that loops continuously without the need for navigation buttons. Instead, I plan to allow users to control the slider using touch gestures (although this functionality is not yet implemented in the code snipp ...

Transferring information via a function to a modal component in VueJS

Seeking advice on passing data to a modal. I'm attempting to pass data to a modal, where a function within a v-for loop gathers the video URL for later opening. The modal is placed outside the v-for loop to prevent all videos from playing the same o ...

Encountering a runtime error in React while making an async call on a NextJS 13 page

I am currently working on implementing async calls using the new app layout in NextJS 13. I have been referring to the latest documentation page. However, I have encountered an error that I can't seem to resolve. https://i.sstatic.net/CpNmu.png Belo ...

Issue with locating elements within calendar pop-up in Cypress

I'm having trouble interacting with the date picker (popup) during my Cypress tests. Despite trying methods like .find() and .get() on various div classes, I keep receiving the error message: Timed out retrying after 4000ms: Expected to find element: ...

Extracting JSON Data into Text Boxes within jQuery UI Dialogs

Let me provide some context to my current issue. Due to the nature of the problem being work-related, I am unable to share much of the code. The task at hand involves working with a jQuery dialog. Essentially, I have a list of names displayed with a boots ...

Ensuring accurate data entry through form validation within a table format

I'm working with a textbox that is part of a table column. My goal is to make sure the entire column is not empty when the Ok button is clicked. If you have any suggestions on how I can achieve this, please let me know. var formatTableMandatoryVa ...

Is there a way to delete a stylesheet if I only have limited information about the url?

I am attempting to dynamically remove a CSS stylesheet using JavaScript or jQuery. I am aware that the target stylesheet is located within the 'head' element and includes the text 'civicrm.css', however, I do not possess the full URL o ...

Tips for customizing the cursor to avoid it reverting to the conventional scroll cursor when using the middle click

When you wish to navigate by scrolling with the middle mouse button instead of using the scroll wheel, simply middle-click and your cursor will change allowing for easy scrolling on web pages. Even though I am utilizing style="cursor: pointer" and @click. ...

Retrieving the chosen date from a calendar using a jQuery function

Hey there, I need help with showing tasks created on a specific date by selecting that date from a full month calendar. https://i.sstatic.net/hbLtp.jpg There are multiple tasks created on the selected date, and I want to trigger a jQuery event to fetch d ...

What causes the truncation of the backslash in the string "videos1_visualisation.mp4"?

Check out this example of AngularJS code I've created. The factory contains a list of video sources. var videoPlayer=angular.module('videoPlayer',[]) videoPlayer.controller("videoplayer",["$scope","videolist",function($scope,videolist) ...

Place 4 divs within 2 divs, with one aligned to the left and the other to the right

I'm currently working on a small project using Angular 2 for an experiment, where I need to place 4 divs, each containing an image, within 2 divs. However, all the divs (with images) are stacked vertically instead of being placed next to each other, ...

"Implementing a Redux structure to enhance audio player functionality and effectively manage error

Imagine I am in the process of developing an audio player that includes a control panel for users to pause/play the currently selected track, along with the actual audio players. This involves actions such as pausing/playing the track, with the audio playe ...

Tips for attaching functions to a fresh SVG element with jQuery?

My jQuery code creates an <svg> element and appends it to a <div>. When I try to access the appended <svg> using each() after the append() function, the event handler doesn't work. However, if I create the <svg> element before ...

Error loading code. Works when manually pasted, but not when executed with JavaScript

After some trial and error, I found that this code works perfectly if I manually copy the content from the class isotope in 1.php to the class grid on this page. However, when I try to use JS to do the same thing, it mysteriously stops working. Any sugge ...