`Switching the selection in ng-selected`

I am having trouble toggling ng-selected options in Angular. I have tried the following approach:

<select ng-model="datacut.ages" multiple>
   <option value="" disabled="disabled">Please Select</option>
   <option value="0-15" ng-click="toggleSelect(datacut, '0-15')" ng-selected="datacut.ages.indexOf('0-15') !== -1">15 and Younger</option>
   <option value="16-19" ng-selected="datacut.ages.indexOf('16-19') !== -1">16 - 19</option>
   <option value="20-24" ng-selected="datacut.ages.indexOf('20-24') !== -1">20 - 24</option>
</select>

Controller:

$scope.toggleSelect = function(dc, str){
    dc.ages.splice(dc.ages.indexOf(str), 1);
    //e.currentTarget.selected = !e.currentTarget.selected;
};

The issue I'm facing is that when I click on an option, it gets selected on mousedown, but unselected on release. The commented out code behaves the same way.

I believe there should be a simple solution to this problem, but I haven't been able to find an elegant one.

Any assistance with this matter would be greatly appreciated.

Edit: Just to clarify - I need to have the option of having no elements selected, so clicking on a single selected element should unselect it. Additionally, I need to be able to select multiple options concurrently.

Answer №1

Utilize the power of ng-model to simplify your code. No need for ng-click or ng-selected. Take a look at my working example on this fiddle

<select ng-model="datacut.ages" multiple>
  <option value="" disabled="disabled">Please Select</option>
  <option ng-value="'0-15'">15 and Younger</option>
  <option ng-value="'16-19'" >16 - 19</option>
  <option ng-value="'20-24'" >20 - 24</option>
</select>

Answer №2

To remove the selected age from the ages model, you should utilize the ng-change directive instead of ng-click or ng-selected. Ensure to retain the ng-model in order to access the value when removing the selected item.

If you need further guidance, refer to this example on Plunker

<select multiple name="ages" unseletable forbiden-opt="datacut.MIN_AGE" ng-model="datacut.chosenAge">
        <option value="" disabled="disabled">Please Select</option>

        <option ng-repeat="age in datacut.ages" value="{{age}}">
          {{age}}
        </option>
      </select>

NOTE: It is recommended to implement this functionality within a directive to properly update the option HTML and successfully unselect the option.

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

When jQuery fails to detach() due to the presence of an input tag

I have a situation where I am trying to rearrange elements within a table. Everything works fine, until I introduce a tag, which triggers this error message:</p> <pre><code>Error: this.visualElement is undefined Source File: http://192. ...

Utilizing Enum Types in Angular Templates

I have a set of server-side enums that I need to send to an Angular application. My goal is to access these enums in the following manner: <select ng-options="type.name as type.value for type in Enums.TYPES" /> I've attempted various methods ...

Error in the Syntax of Project Image Slider

I'm encountering an issue with a WordPress script called Project Slides. Initially, this script was working fine but suddenly stopped. After investigating in the console, I found the following error: VM138 plupload-image.js?ver=4.2.2:67 Uncaught Err ...

Ways to retrieve Payload following the Request url access

Currently utilizing Selenium with Python to conduct website testing, I successfully accessed the Request link and now aim to access the Payload. Below is an image displaying the process: view image description here driver = webdriver.Chrome(options=option) ...

What is the process for producing multiple objects in JSON format and then accessing them from within <g:javascript> in Grails?

My goal is to add two select boxes within the results div using Ajax. I have a function named ajaxFun that retrieves values for the select boxes. However, I am struggling with rendering multiple objects as JSON and then retrieving them in my JavaScript fun ...

The middleware in Express.js is failing to execute the next function

I have been attempting to run a post function that contains a next(); within the code. To solve this issue, I have exported the function's definition from another file and am trying to call it through an express router. Unfortunately, the function is ...

Looping through Angular injection

I am facing an issue with my AngularJS setup and I am unable to find a straightforward solution. My authentication process involves two tokens: Access token and Refresh token, managed by two separate services - Auth and Api. When a user accesses data usin ...

Custom AngularJS directive: dynamic template rendering using scope value (ng-bind-html)

I am currently working on a directive which looks like this: ... template: function(element, attrs) { var htmlTemplate = '<div class="start-it" ng-if="isVisible">\ <p ng-bind-html="\'{{customDynamicText}}\&a ...

What is the best javascript framework to pair with twitter bootstrap?

After dabbling in twitter bootstrap, I discovered its impressive array of UI components. Interested in incorporating it into a project, my quest for a compatible javascript framework has left me torn between angularjs, backbonejs, and emberjs. Although I ...

Tips on saving additional parameters in an API URL with AngularJS

Here is my AngularJS function code: $scope.cardcall = function (cardtype) { $scope.cityname=cityname; $http({method: 'GET',url: '/api/v1/asasas&filterBy=cardNames&filterByValue='+cardtype.key}).success(funct ...

Exploring the fundamentals of Angular.js: A comparison of Services, Factories, and Controllers along with Directives and Behavior

I recently came across an article discussing the use of directives, services and controllers in Angular. While it was informative and helpful, it left me feeling a bit lost about the best structure for an angular application. I could really use a sanity ch ...

VueJS method for making an HTTP GET request

Attempting to make an http get request using Vue js. I can't seem to find any issues with the logic, although I'm not very experienced with vuejs. Continuously encountering these two errors: [Vue warn]: Error in mounted hook: "TypeError: Cann ...

Issue with rendering Angular templates

Having just embarked on my AngularJS journey, I'm currently facing an issue with this specific code snippet. The following is an excerpt from my JavaScript file named cribsController.js: angular .module('ngCribs') .controller('cribsCo ...

Unable to display image on React page using relative file path from JSON data

Greetings, this is my initial post so please forgive me if I have missed any important information. I'm currently in the process of creating a webpage using react. My goal is to display content on the page by iterating over a relatively straightforwa ...

Include two additional elements for action in a list

In my React project, I've created a list with the following elements: Avatar Text Edit icon Delete icon I managed to set up the structure successfully up until the delete icon. Now, how can I properly add it without overlapping the edit icon? Both ...

Interact with the exe/jar files on a remote machine using JavaScript

I've been tasked with finding a way to access an executable file (or any file located in a specific location like the C drive) directly from a web browser. The idea is to have a button on a webpage that, when clicked, will run the executable and pass ...

Even after assigning the class "img-fluid" to my image, it still fails to properly adjust to the screen size

I added the class "img-fluid" to my image in Bootstrap, but it's not fitting on my webpage. What should I do? <img src="images\406201.jpg" class="img-fluid" alt="..."> <div style="margin-top: 0p ...

Guide to making a dropdown menu that pulls information from a text box and displays the location within the text

I'm currently working on a unique dropdown feature that functions like a regular text field, displaying the text position. To achieve this, I've constructed a hidden dropdown menu positioned beneath the text field. My goal is to develop a jQuery ...

Error: Google Plus Cross-Origin Resource Sharing Issue

I recently developed an AngularJS application that utilizes Google's server-side flow for authentication. The issue arises when my AngularJS app is hosted on one server and the Rest API is hosted on another. After successfully logging in, I encounter ...

Encountering limitations in accessing certain object properties with the openweathermap API

As I integrate axios into my react application to retrieve weather data from the openweathermap api, I'm encountering some issues with accessing specific properties from the JSON object returned by the API call. For instance, I can easily access data. ...