AngularJS - choosing the ng-model's index value

I'm looking to retrieve the selected item(s) from a select control along with their values or titles. Once the user has made their selections from the dropdown menu, I want to be able to determine the number of items selected and display their titles or values.

Below is a snippet of the HTML code on my page:

<select ng-model="selectedValues" multiple>
            <option >All Booth</option>
            <option> Washroom</option>    
 </select>

 <button ng-click="apply()" type="button>Apply</button>

Here's an example of the code in my controller:

$scope.apply = function () {
// Retrieve the number of selected items and their titles or values

}

Any suggestions on how I can accomplish this? Thank you.

Answer №1

Feel free to test out the demo:

const myApp = angular.module('myApp', [])

myApp.controller('appController', function ($scope) {

    $scope.applyChanges = () => {
        if($scope.selectedValues !== undefined && $scope.selectedValues.length > 0) {
            // Retrieve selected items and their count
            let selectedTitles = $scope.selectedValues; // Get titles or values
            let numberOfSelectedItems = $scope.selectedValues.length; // Get number of selected items

            console.log("Total items selected: " + numberOfSelectedItems + " - Titles: '" + selectedTitles.toString() + "'");
        } else {
            console.log("No item has been selected");
        }
    }

});
<!DOCTYPE html>
<html>

  <head>
    
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js"></script>
   
  </head>

  <body ng-app="myApp" ng-controller="appController">
     <select ng-model="selectedValues" multiple>
            <option>All Items</option>
            <option>Main Category</option>    
 </select>

 <button ng-click="applyChanges()" type="button">Apply Changes</button>
  </body>

</html>

Answer №2

Instead of using ng-repeat, consider utilizing the ngOptions attribute when working with the select element in AngularJS. To learn more, visit the ngOptions documentation.

See Below for a Working Demo :

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl',function($scope) {

    $scope.items = [
    {
      title: 'All Booth',
      value: 'All Booth'
    },
    {
      title: 'Washroom',
      value: 'Washroom'
    }
    ];
    $scope.apply = function(selectedValues) {
        var selectedValuesLength = selectedValues.length;
        console.log(selectedValuesLength); // selected items count
        for(var i in selectedValues) {
            console.log(selectedValues[i]); // selected items title
        }
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
    <select multiple="true" ng-model="selectedValues" ng-options="item.value as item.title for item in items">
    </select>
    <button ng-click="apply(selectedValues)" type="button">Apply</button>
</div>

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

Navigating through the complexities of scoping in JavaScript when integrating Node.js

Currently, I am working on an express.js application without using mongoose. My goal is to create a function that can handle calls to MongoDB, pass parameters to it, and retrieve data from the database. However, I have encountered a problem with the foll ...

Overlaying content: Innovative dropdown menu design

My goal is to create a dropdown box that overlays the content of a div when an icon within it is clicked. However, currently, the dropdown box is pushing down the content of the div instead of overlaying it. I have tried adjusting my CSS by setting some el ...

Axios Instance class request cancellation

In my Redux-saga project, I am working on implementing a polling function where I need to make a request every second. If there is no response from the endpoint, I want to cancel the previous request and initiate a new one using Axios client. I have organi ...

typescript in conjunction with nested destructuring

ES6 has definitely made coding more efficient by reducing the number of lines, but relying solely on typescript for everything may not be the best approach. If I were to implement type checking for arguments that have been destructed multiple levels deep, ...

ZK: maintaining session connectivity

When I need to redirect to a tel:**** link in ZK and then redirect the user to another page after the call, I encounter a problem. Every time I click on the link, ZK interprets it as leaving the browser, which results in my client session ending automatica ...

AngularJS: implement functionality to trigger action when div is visible

I am currently working on developing a website using AngularJS and I have come across an interesting problem. I am able to show or hide a div element successfully through Angular, but now I need to make dynamic substitutions within this div. However, I wan ...

Having trouble getting async and await to function properly

Why is my code not waiting for validation and running the else part immediately? Can you help me find the mistake? async validateBeforeSubmit(event) { await this.$validator.validateAll().then(result => { if (result) { ...

In order to toggle a div property on and off with each click, you will need to use an onclick JavaScript function

I have an HTML button that triggers a JavaScript function when clicked, revealing a hidden div by changing its display property. The current setup is functional and achieves the desired outcome. However, I now wish to modify the functionality so that subs ...

The code is triggering IE 8 to switch to compatibility mode resembling IE7

I have created a custom javascript function that generates a pop-up, and I am invoking this function in my code. However, every time I click the button, the browser switches to IE 7 compatibility mode and the pop-up appears behind the button. Below is my ...

The upload directory in KCFinder can be accessed and selected using a URL

Issue: While using the link to open kcfinder as defined in kcfinder, I encountered a problem. The link is intended to open kcfinder with the provided parameters: window.open('/kcfinder/browse.php?type=files&dir=files/public&subDi ...

Enhancing JSON data in Datatables with additional text

I'm currently looking for a way to insert some text into my data before generating a table using jQuery DataTables. As an example, if my JSON data looks like [1,5,6,12], I would like it to be displayed as [1 seconds, 5 seconds, 6 seconds, 12 seconds] ...

jQuery DataTable error: Attempted to set property 'destroy' on an undefined object

<script> $('#archiveTable').DataTable({}); </script> <table id="archiveTable" datatable="ng" class="table table-sm" style="color:black"> <!--some code--> </table> This is a snippet of HTML code Upon checking t ...

Preventing data duplication when refreshing a webpage using Node.js

I am currently utilizing Mustache and Nodejs to populate a dropdown menu with a list of options on my website. However, every time the page is refreshed, I encounter duplicate entries in the dropdown. How can this issue be resolved? I trust that my inquiry ...

The admin-ajax.php file in WordPress consistently fails to return any value other than

I developed a WordPress ajax plugin, but I am facing an issue where admin-ajax.php always returns 0 and the plugin doesn't work as expected. Here is the code I have implemented: add_action( 'wp_ajax_example_ajax_request', 'example_aja ...

Mirror the input text to another input within a for loop

I have a list of questions displayed, each with an input field for entering a phone number. How can I use jQuery or JavaScript in a for-loop to mirror the text entered in the first phone input box to all subsequent phone input boxes? ..Enter your phone... ...

"Automatically insert a new row into the table if the cell loses focus and is not left

Can someone assist me with adding a table row dynamically when a cell is filled and the input focus is lost? My JavaScript skills are not strong. Here is a link to the form: JSFIDDLE <table class="table table-timesheet" ng-controller="TimesheetCtrl"> ...

Exploring the intersection of points within an aframe

When working with a point in 3D space, it can be difficult to interact with it using a cursor or mouse. However, in three.js, there is an example (https://threejs.org/examples/webgl_interactive_points.html) where the mouse can easily interact with points ...

Exploring the method of creating multiple nested states within various parent components while utilizing identical templates

I have developed a mobile site for purchasing, renewing, and transferring domains. The app consists of 4 templates that work together in a functional chain. Buy : Search -> (login if necessary?) -> Pay -> Confirmation Renew : Choose -& ...

Build a stopwatch that malfunctions and goes haywire

I am currently using a stopwatch that functions well, but I have encountered an issue with the timer. After 60 seconds, I need the timer to reset to zero seconds and advance to one minute. Similarly, for every 60 seconds that pass, the minutes should chang ...

Using `window.location.href` will terminate any pending asynchronous calls to the API

Before all async calls to the API are completed, window.location.href is triggered when the code runs. Setting a breakpoint on the location resolves the issue. How can I ensure that all calls are finished before invoking window.location.href? Code: const ...