How can you disable an 'option' HTML5 element using the AngularJS methodology?

How can I disable an 'option' element in HTML5 using AngularJS?

Currently, I am working with AngularJS v1.2.25.

Here is the Plunk Link for reference: https://plnkr.co/edit/fS1uKZ

<!-- CODE BEGIN -->
<!DOCTYPE html>
<html>
    <head>
        <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9b8b7beacb5b8abf7b3aa99ebf7e9f7e9">[email protected]</a>" data-semver="2.0.0" src="https://code.angularjs.org/2.0.0-beta.6/angular2.min.js"></script>
        <link rel="stylesheet" href="style.css" />
        <script src="script.js"></script>
    </head>
    <body>
        <select>
            <option value="volvo">Volvo</option>
            <option value="saab">Saab</option>
            <option value="opel">Opel</option>
            <option value="audi">Audi</option>
        </select>
        
        <!-- More select elements here -->
        
    </body>
</html>
<!-- CODE END -->

I'm building a 'form' with multiple 'select' elements containing 'option' tags.

All 'option' tags share the same attributes across these 'select' elements.

The goal is to let users rank car manufacturers by disabling the selected option in all 'select' elements.

I came across a solution using jQuery, but does that align with AngularJS practices? (Disable option in select)

Considering AngularJS has 'jQuery Lite', should I follow this approach or explore other options?

There's documentation on ng-disabled directive at AngularJS site: htt9$://docs.angularjs.org/api/ng/directive/ngDisabled

You can also check out this Plunk example from AngularJS team: htt9$://plnkr.co/edit/?p=preview

I want to avoid modifying core AngularJS files and instead focus on utilizing ng-model and/or ng-disabled without causing technical debt.

Should I separate ng-model and ng-disabled or create a custom filter instead?

Coming from a jQuery background, I aim to adhere to AngularJS best practices and minimize technical debt accumulation.

Answer №1

If you want to disable a select option in Angular, use ng-disabled="expression". Check out this plunker for an example.

You can create 4 select elements like this:

<select ng-model="model.selected1">
  <option ng-repeat="c in model.options" value="{{c.value}}" ng-disabled="model.should_disable(c, 1)">{{c.label}}</option>
</select>
<select ng-model="model.selected2">
  <option ng-repeat="c in model.options" value="{{c.value}}" ng-disabled="model.should_disable(c, 2)">{{c.label}}</option>
</select>
<select ng-model="model.selected3">
  <option ng-repeat="c in model.options" value="{{c.value}}" ng-disabled="model.should_disable(c, 3)">{{c.label}}</option>
</select>
<select ng-model="model.selected4">
  <option ng-repeat="c in model.options" value="{{c.value}}" ng-disabled="model.should_disable(c, 4)">{{c.label}}</option>
</select>

Remember to define your list of options in the model.options variable.

var model = $scope.model = {
    options: [
      {label: 'Volvo', value: 'volvo'},
      {label: 'Audi', value: 'audi'},
      {label: 'Saab', value: 'saab'},
      {label: 'Opel', value: 'opel'},
    ],
    should_disable: should_disable
}

The should_disable(c, num) function should return true if the car c is selected in any other <select> element besides num.

function should_disable(c, selectnum){
    var other_selectnums = [1,2,3,4].filter(function(n){
      return n != selectnum;
    });
    var is_selected_somewhere_else = false;
    for(var i=0; i<other_selectnums.length; i++){
      var otherselectnum = other_selectnums[i];
      if(c.value == model['selected'+otherselectnum]){
        is_selected_somewhere_else = true;
        break;
      }
    }
    return is_selected_somewhere_else;
}

For a fully functional example, check out this plunkr.

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 trying to authorize my channel, the JSON data is coming back as a blank string

I've encountered an issue with my JavaScript code: Pusher is throwing the error message "JSON returned from auth endpoint was invalid, yet status code was 200. Data was: ", indicating empty data. I have double-checked the broadcasting service provider ...

Troubleshooting Display Issue with Nested Div Selection in jQuery Tooltips

I have a long list of data consisting of 30-50 rows, each row needing its own distinct tooltip. Creating unique IDs for each row would require unnecessary JavaScript code. My goal is to utilize jQuery to retrieve the tooltip from the nested <DIV> wit ...

jQuery Form Validator: requiring double submission

I've been working on implementing the Form Validator using Jquery. After some testing, I noticed that I have to click the submit button twice before the validation kicks in. Why is that? The script is housed in a separate file and included in my proj ...

Steps to store radio button selections in local storage

I have a quiz that includes radio buttons, and I need to save the answers on my local storage. However, I am currently stuck and unsure of what else to do. I am learning, so please don't be too hard on me. Thank you! Here is the code I have written s ...

Displaying a specific div depending on the selected radio box in Angular JS

I am facing an issue with radio buttons and the 'delete' text while using ng-repeat in AngularJS. My requirement is to display the delete text based on the radio button that is checked. So, whenever a radio button is clicked, the corresponding de ...

Why does the ng-click function fail to execute when using the onclick attribute in AngularJS?

Whenever I try to invoke the ng-click function using onClick, I encounter an issue where the ng-click function is not being called. However, in my scenario, the model does open with the onClick function. //Function in Controller $scope.editProductDetail ...

Using NodeJs to pass values to a callback within a condition statement and retrieve the returned value

Within my routing file, I have implemented a condition where an external function is used to compare two values: obj.id === getId. Based on whether this condition evaluates to true or false, the view is rendered, or the user access is blocked. The functio ...

Javascript problem with closing the browser window in Selenium WebDriver

Here are a couple of inquiries: Firstly: Is there a method to initiate the browser on a specific URL (instead of about:blank) while also setting the history length to 0 when starting on that URL? Secondly: I suspect this question is related to the one me ...

Storing Objects in MongoDB using Node.js

I am working on an application where I need to store an object for later execution of functions. This object essentially holds the data of a cron job. var cronJobObject = schedule.scheduleJob(new Date(2018, 0, 19, 15, 15, 0), function() { console.log( ...

Adjusting the size of content tags depending on their popularity

Currently, I am working on setting up a basic tagging system by following the database structure provided in this Stack Overflow post. My goal is to create a single page that showcases all the tags, with each tag being visually scaled based on its popular ...

Ways to close jQuery Tools Overlay with a click, regardless of its location

I have integrated the Overlay effect from jQuery Tools to my website, with the "Minimum Setup" option. However, I noticed that in order to close it, the user has to specifically target a small circle in the upper right corner which can affect usability. It ...

Combining vueJS and webpack to bring in fonts, CSS styles, and node_modules into your project

I've recently started working with Vue.js and Webpack, and I'm facing some challenges regarding the correct way to import and reference fonts, CSS, and node_modules in my project. My project structure looks like this, as set up by vue-cli: buil ...

Encountering an issue with Firebase Cloud Messaging

I am struggling to implement a push notification trigger whenever a document field is updated. As a newcomer to node.js, I am facing challenges in debugging what seems like a simple function. Below is the code snippet: // Cloud Functions for Firebase SDK ...

Place the object into a vacant area with the help of jQuery Sortable

I am using jQuery Sortable and it's functioning well. However, I have encountered a small issue that I need help with.    I have two blocks where elements from one block can be moved to the other. The problem arises when all the elem ...

Calculate the cumulative values in ng-repeat using AngularJS

I used ng-repeat to iterate through a JSON array. I calculated the number of nights by utilizing the dayDiff() function. Now, I need to find the total number of nights for all invoices. My project is built with AngularJS. Is there a way to retrieve the to ...

Dynamic fields added using JavaScript are not recognized by PHP

I have a MySQL database where orders are stored along with various activities. My PHP/HTML page retrieves these activities when an order is clicked and allows users to modify them using a form. Upon submission, another PHP file updates the database by loop ...

Is it possible to prevent copying dates within tabs using Angular-UI Bootstrap?

I have set up a basic Tab using Angular-ui bootstrap. Within the tab, there is a 'date input' <input type="date"/> <tabset> <tab heading="Tab A"> Date Input Inside Tab</br> Date 1:<input type="dat ...

Creating elegant Select Dropdown Box in AngularJS without relying on images

I am currently working on an angular page and have implemented a dropdown with ng-Options to fetch and set values successfully. However, I am now looking to enhance the appearance of this dropdown. After exploring options like ui-select, I realized that be ...

The functionality of Vue JS v-attr="expression1 && exp2 && exp3" seems to be malfunctioning

Why aren't Vue JS v-attr=“expression1 && exp2 && exp3” working? I've attempted using ${&}${&}, #{&}#{&}, &amp;&amp;, and even #{&amp;}#{&amp;} The code can be found on JSFiddle <div id="dem ...

Numeric keypad causing issues with setting minimum and maximum lengths and displaying submit button

I designed a password pin page that resembles a POS NUMPAD for users to enter their password. I am struggling to make the condition specified in the JavaScript function properly. Rule: Hide the submit button if the minimum input is less than 4 characters ...