"Need to remove all chosen selections within an ng-repeat loop? Here's how

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.cars = [{
      model: "Ford Mustang",
      color: "red"
    },
    {
      model: "Fiat 500",
      color: "white"
    },
    {
      model: "Volvo XC90",
      color: "black"
    }
  ];
  $scope.cl = function() {
    alert($scope.ename)
    $scope.selectedCar = ""
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">

  <p>Select a car:</p>
  <div ng-repeat="y in cars">
    <select ng-model="selectedCar">
    <option ng-repeat="x in cars" value="{{x.model}}">{{x.model}}</option>
    </select>
  </div>
  <h1>You selected: {{selectedCar}}</h1>
  <button ng-click="cl()">click</button>
</div>

Due to ng-repeat in the code above, each select box has its own scope, making it difficult to clear all selected options at once.

Do you have any suggestions on how to resolve this issue?

Answer №1

It appears that the issue lies in the misuse of the ng-repeat directive. With the current setup, all three select boxes are sharing the same ng-model, leading to confusion with the displayed values. To resolve this, I have updated the ng-model to an array so that each selection is tracked individually, allowing the entire selection to be cleared by emptying the array.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.selectedCar = [];
  
  $scope.cars = [{
      model: "Ford Mustang",
      color: "red"
    },
    {
      model: "Fiat 500",
      color: "white"
    },
    {
      model: "Volvo XC90",
      color: "black"
    }
  ];
  $scope.cl = function() {
    $scope.selectedCar = []
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">

  <p>Select a car:</p>
  <div ng-repeat="y in cars">
    <select ng-model="selectedCar[$index]">
    <option ng-repeat="x in cars" value="{{x.model}}">{{x.model}}</option>
    </select>
    <span ng-if="!selectedCar[$index]">Choose a car</span>
  </div>
  <h1>You selected: {{selectedCar}}</h1>
  <button ng-click="cl()">click</button>
</div>

Answer №2

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<body>
  <div ng-app="myApp" ng-controller="myCtrl">
    <p>Please choose a car:</p>
    <div ng-repeat="y in cars">
      <select ng-model="selectedCar[$index]">
        <option ng-repeat="x in cars" value="{{x.model}}" >{{x.model}}</option>
      </select>
    </div>
    <h1>Your selection: {{selectedCar}}</h1>
    <button ng-click="deleteSelection()">Clear selection</button>
  </div>

  <script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $rootScope) {
      $scope.selectedCar = {};
      $scope.cars = [{
          model: "Tesla Model S",
          color: "black"
        },
        {
          model: "BMW X5",
          color: "blue"
        },
        {
          model: "Audi A4",
          color: "silver"
        }
      ];

      $scope.deleteSelection = function(e) {
        $scope.selectedCar = {};
      };

    });
  </script>

</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

Error 406 occurred when attempting to consume a REST service in org.springframework.web

I am encountering a 406 response error with "HttpMediaTypeNotAcceptableException" when trying to call a REST service from AngularJS. AngularJS REST Call $http.get('/MongoMicroServices-0.1.0/user/getByMailId/' + $scope.username).then(function(re ...

Display a div when hovering over an image using jQuery

I've spent a good 30 minutes searching on Stack Overflow for a solution, but I haven't been able to find it yet. It's possible that I'm not sure what exactly to look for. Essentially, I have a div that contains an image and some text. ...

Exploring the world of lighting and shadows in WebGL and Three.js

I'm having difficulty focusing lights on specific targets, specifically the main character, while also darkening the background. Additionally, I'm experiencing issues with the shadows not working properly in my code snippet related to lights and ...

Backend framework

Currently, I am in the process of developing a robust web application that heavily relies on JavaScript and jQuery, with ajax functionality included. Additionally, there will be a database in place, managed using mySQL with several tables. I'm undeci ...

Whenever a user tries to retrieve a page using ajax and then proceeds to submit the form associated with that page, they encounter

In my addQuestions.php file, I have four options available - single, multiple, matrix, and true false type questions with values 1-4 assigned to each respectively. To dynamically load the appropriate question type based on user selection, I am using AJAX w ...

Employing fetch to send a POST request for inserting data into a JSON server database

I'm currently experimenting with adding new data to my simulated database using JSON server. However, I've encountered an issue where the input information is not being added when I execute the function. Although an ID is generated in my databas ...

Customize dynamically loaded data via AJAX

I have a webpage that is loading a table from another source. The CSS is working fine, but I am facing an issue editing the table using jQuery when it's loaded dynamically through a script. It seems like my changes are not getting applied because they ...

Using vue.js to pass route parameters to a component

I'm encountering an issue with passing a route param directly into a component. Despite following various sets of instructions from the documentation (including using the Composition API as shown in the code snippet below), I continue to receive undef ...

Utilizing Selenium and JavaScript to discover and extract the subject fields within a table

In my sent message list, I am trying to display the subject fields of all messages using Selenium and JavaScript (not Java) for coding. Here is the code snippet: <table class="messages"> <tbody><tr class="section-heading"> < ...

Passport for Node.js: Securing User Access

(code updated with serialization functions - still redirecting to /failedRedirect) I'm attempting to establish basic username/password authentication using the passport library, but encountering difficulties. Even though I have set up the code to alw ...

The date entered in an HTML input is being interpreted as "incorrect" by the system

Upon inputting 3/15/2019 as the date and then checking the time with console.log(fromDate), the output appears as Thu Mar 14 2019 19:00:00 GMT-0500 (Central Daylight Time). Why is it not showing Fri Mar 15 2019 00:00:00? Could this be related to the tim ...

An automated feature that smoothly transitions a large image onto the screen

I came across a plugin, possibly a slideshow plugin, that smoothly slides a large image along the y-axis. It's hard to explain, but imagine the visible image is only 600px by 300px, while the actual image is 600px by 600px. This plugin would scroll t ...

Incrementing numbers automatically within a JSON object while iterating through a for loop

I am struggling to figure out how to append the var i to the left side of the object declaration. This error is causing me troubles. Any assistance in resolving this issue would be greatly appreciated. If you have any alternative solutions, I am open to e ...

What are the best ways to stop jQuery events from propagating to ancestor elements?

I have a collection of nested UL's that follow this structure: <ul class="categorySelect" id=""> <li class="selected">Root<span class='catID'>1</span> <ul class="" id=""> <li>First Cat<span ...

transmit an extensive base64 encoded string to the webapi

While sending a post request to the webapi controller using my AngularJS, one of the parameters includes a base64 string value. $scope.upload = function(Id, formdata) { debugger; if ($scope.logoattachments[0].fileSize != '&apos ...

Utilize text-to-speech technology to convert the output results into

Looking for a way to live stream a text to speech message triggered by a button press on your website? Unsure how to accomplish this with Node.js and generate the file after the button press? Let's explore some solutions together. ...

unable to render the JavaScript code

Utilizing JavaScript post an ajax request to showcase the data in a div using new JS content. The example code is provided below: //ajax call from a.jsp var goUrl = "/testMethod/getTestMethod; var httpRequest=null; var refreshCont ...

Show a variety of randomly selected pictures from various sources using the command image/next

I'm in the process of building a basic news aggregation website using Next.js. I’ve run into an issue where I need to include specific domains in my next.config file for the Image component to work properly. The problem is, the URLs for the images o ...

Place the Drawer element at the bottom of the menu

Is there a way to position the menu point at the bottom of the screen? It would be great if we could easily customize the style of the navigation options for each element. Check out my App Navigator below: const AppNavigator = createDrawerNavigator( ...

What's the Secret Behind the Mysterious Parameter in setState?

Currently enrolled in a TypeScript + React course where I am working on developing a todo list application. However, my query is related to a specific feature of React. Within the function for adding a new Todo item, there is a statement declaring a funct ...