Refresh the default selection in the select list after applying a filter

Trying to customize a drop down list of options based on radio button selection.

<div>
    <div ng-controller="sampleCtrl">
        <label>
            <input type="radio" name="type" ng-value="1" ng-model="selectedType" />A</label>
        <label>
            <input type="radio" name="type" ng-value="2" ng-model="selectedType" />B</label>
        <select ng-model="selectedOption" ng-options="option.id as option.name for option in options | filter:{type:selectedType}">
            <option value="">&lt;Select&gt;</option>
        </select>
        <hr/>
        <div>Type: {{selectedType}}</div>
        <div>Option: {{selectedOption}}</div>
    </div>
</div>

function sampleCtrl($scope) {

    $scope.selectedType = 1;

    $scope.selectedOption = 0;

    $scope.options = [{
        id: 1,
        name: 'bread',
        type: 1
    }, {
        id: 2,
        name: 'sugar',
        type: 2
    }, {
        id: 3,
        name: 'tea',
        type: 1
    }, {
        id: 4,
        name: 'coffee',
        type: 2
    }, {
        id: 5,
        name: 'butter',
        type: 2
    }];
}

Link to the jsFiddle

A default '' option is set to display when the user changes the type. Filtering works, but model not updating when filter changes. Please assist. Thank you.

Answer №1

This solution provides the necessary functionality: Solution

Essentially, whenever the user switches between radio buttons to change the type, a function called watch is activated which resets the selected option.

As a result, switching between types ensures that the model linked to the chosen option is reset.

$scope.$watch('selectedType', function (newValue, oldValue) {
    if (newValue !== oldValue) {
        $scope.selectedOption = null;
    }
});

Answer №2

Summarizing @callmekatootie's explanation:

In this case, the parameters newValue and oldValue are unnecessary:

$scope.$watch('selectedType', function() {
    $scope.selectedOption = 0;
});

I also reverted back to the initial value instead of $scope.selectedOption = null since the $watch function is called during page load. This adjustment may help avoid potential issues in the future.

JSFiddle link

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

Tips for ensuring JavaScript code runs in a specific sequence

On my webpage, I have implemented a feature where users can click a button to fetch data using an xhr get request. During the loading and parsing of this data, I want to display a loading message that will be replaced with the actual data once it is ready. ...

NextJS displays outcomes as per query parameters obtained from an external API

I have set up my NextJS app to connect to a rest API. The API returns results based on different filters in the query string, such as: /jobs /jobs?filter=completed /jobs?filter=upcoming /jobs?filter=cancelled On my NextJS page, I have a few buttons that I ...

Node.js and Express.js are being used in conjunction with Angular to create a server-side controller that fetches all data. However, there seems to be an issue as the

"findByStaff" and "findOne" are working correctly, however, "findAll" is not returning any data. I expected findAll to retrieve all courses from mongodb $scope.findByStaff = function() { $scope.courses = Courses.query(); }; $scope.fin ...

In search of grabbing an image from a list item and relocating it to sit before the division tagged with class "event-title"

I am struggling with selecting each list element within the ul and moving the image inside the div class="event-details" above the div with the class="event-title". This adjustment is necessary for achieving the desired styling since the wordpress Event pl ...

ES6: Utilizing tagged templates for embedding nested HTML elements

Currently in the process of familiarizing myself with JavaScript and testing out its tagged template literals feature. <p> Handlebars? Tagged template literals? <span> That is a question. </span> </p> The above snippet showcases ...

I am looking to update the appearance of a button dynamically in Vue.js based on changes to an

Is there a way to toggle a visible button when the array changes? I'm having trouble implementing this. What is the most effective method? Check out my example below: https://codesandbox.io/s/relaxed-poincare-vv6xh?file=/src/components/HelloWorld.vu ...

Guide to sending a binary body in a POST request using Meteor.js

I've been struggling with a challenging issue in Meteor.js that I'm hoping to resolve. My goal is to make API calls to a face detection open API service by sending an image and receiving a JSON object in return. However, I have hit a roadblock as ...

Class for non-invalid feedback in Bootstrap

How can I represent the concept of an invalid input field using a specific class? I am trying to create a form where, under a certain input field, there will be a placeholder indicating that only 3 characters are allowed. If the validation fails, I want to ...

Limiting the textfield to 100 characters while allowing special characters in React.js

I am working with a text field that can accept the following types of values: >35% <=60% =55% =100% My goal is to set the maximum limit of the numbers to 100. How can this be achieved? Below is the code for the textfield in question: <TextField ...

What is the best way to render a view, hide parameters from the URL, and pass data simultaneously?

In order to display the current view: statVars["sessions"] = userSessions; res.render("statsSessions", statVars); Nevertheless, I must find a way to hide the URL parameters from showing up in the browser's address bar (these parameters are sourced ...

Displaying a newly inserted span element

When seeking advice on adding a click event to dynamically added elements, I discovered the use of on() for event delegation. Despite this, I am encountering difficulty targeting the dynamically created content, particularly a span with a class desc. This ...

Display custom modals in React that showcase content for a brief moment before the page refreshes

I recently developed a custom modal in React. When the Open button is clicked, showModal is set to true and the modal display changes to block. Conversely, clicking the Close button sets the display to none. However, I noticed a bug where upon refreshing ...

Having trouble getting the if statement to run with JavaScript Closures?

Check out this code snippet: let url = URL; let imageURL = ''; $.getJSON("https://graph.facebook.com/?id="+encodeURIComponent(url)+"&scrape=true&method=post", function (data) { let json_data = JSON.stringify(data); json_data ...

Whenever the page is refreshed, the props in my application are dynamically updated thanks to the getStaticProps function I utilize

Currently, I am in the process of learning nextjs as a beginner. Through the utilization of the getStaticProps function, I have come to understand that data fetching occurs only once at build time and the values remain static thereafter. Despite this, I ...

In Mozilla Firefox, the form-control with select tag shows the text, while in Chrome, the same component does not display it

I am currently using Angular 5.x in combination with the select tag and optgroup, along with Bootstrap 4.1.x This is how my component.html looks like: <select size="15" class="form-control mr-4"> ...

Is there a way to conceal 'private' methods using JSDoc TypeScript declarations?

If we consider a scenario where there is a JavaScript class /** * @element my-element */ export class MyElement extends HTMLElement { publicMethod() {} /** @private */ privateMethod() {} } customElements.define('my-element', MyElement) ...

For each individual category in the mongoose database, conduct a search

Seeking assistance with mongoose scope issue User.findById(req.user.id, (err, result) => { var cartProduct = []; result.cart.map(async (item) => { //item represents the following object: productId: "product-id", quan ...

Customize AngularJS: Make the default child view for UI-View stand out

I came across a guide on how to set up nested states in AngularJS using UI Router, and followed it to create a page with two child views. Now that everything is set up, clicking on specific links displays the subviews as expected. Below is my app.js file ...

How can I connect a React component to a static HTML page?

Currently, I am working on a React + Redux application and have come across an issue. I am trying to create a link to a privacy.html page that is located in the root of the project alongside index.html (which is the React app). The problem I'm facing ...

Creating dynamic pagination in React using a variable length loop

I'm currently implementing pagination using react ultimate pagination. When a page number is clicked, I update a variable to display the necessary content. The challenge arises from having a loop with a variable number of elements, making it impossibl ...