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

Styling Challenges with CSS/AngularJS Accordion in Footer

I want to create a page layout as shown below: +---------------------------+ | Auto-fill / v scrollable ^| | || | || | v| +---------------------------+ | Fixed [][][] ...

Obtaining Data from CRM 2011 with the Power of jQuery and JavaScript

Currently, I am facing an issue while attempting to retrieve data from CRM 2011 using jQuery. Despite my efforts, I am unable to successfully fetch the desired data. Below is the code that I have been working on: function GetConfigurations() { var oDataP ...

Exploring composite search conditions in MongoDB with JavaScript

Being a newcomer to Node JS and mongo DB, I am currently working on a project that involves fetching data from mongo db using a JavaScript file. The challenge I am facing is to search multiple columns in order to retrieve the desired results. Initially, w ...

I'm having trouble with my controller - not sure what the problem is

My controller seems to be malfunctioning. I have created a controller but it is not functioning properly. Even though I have reviewed it multiple times, the issue persists. Could someone please assist me with this problem? Angular Code var myPanelSearch ...

Creating dynamic <a> tags using JavaScript

My current view includes a div tag with 2 links - one for displaying the page in English and another for Arabic. I want to modify it so that if the page is already in English, only the Arabic <a> tag will show, and vice versa if the page is in Arabic ...

Converting JSON data into an array of JavaScript objects

Here is some of the JSON data I have: [ { "items": [ { "retailername": "Zop Now", "value": 475 }, { "retailername": "Snap Deal", "value": 265 ...

Leverage JavaScript to showcase Django object on the webpage

I am trying to achieve the following using javascript: when a row is clicked, it should retrieve the index and display the object at that index. This functionality works in a django template. <div>{{ project.0.customer_name}}</div> <div> ...

What is the best way to access an external array using ng-repeat in AngularJS?

My dataset consists of 3 separate arrays. "areas": { "default": [ { "area": "Master Bedroom", "uuid": "986e3f42-1797-49ae-b060-181a33b9", "description": "", "new": [ { "value": "986e3f42-1797-49ae-b060-181a3 ...

A guide to deactivating the Material UI Link API element

Previously, I relied on Material UI's Button component with a disable property that allowed the button to be disabled based on a boolean value. However, I now want to use the Material UI Link component, which resembles a text link but functions like a ...

Unable to stop submission as a result of ajax verification

As someone new to java and jquery, I am facing a challenge with the code below: $(document).ready(function() { //Prevent SUBMIT if Session setting = On (Ajax) $('#formID').submit(function(e) { var prevent = false; $.ajax({ type: ...

What is the method for including the sources directory within the require() scope in npm?

Upon examining my directory structure, the following layout is revealed: package.json /src a.js /test test_a.js The contents of package.json are as follows: { "name": "foo", "scripts": { "test": "mocha" }, "devDependencies": { "mocha ...

Ways to retrieve information beyond the scope of the 'then' method

One issue I am facing involves a piece of code that is only accessible inside of the 'then' function. I need to access it outside of this block in order to utilize it in other parts of my program. $scope.model = {'first_name':'&ap ...

Safely transmitting client-side encrypted information between individuals

I am developing a service that will keep personal information about a specific user, which should only be accessible by the author and the intended recipient. I want to encrypt the data on the client-side and store the encrypted version on the server. Res ...

Using Javascript code within functions.php

I am facing an issue with the code below; function add_js_functions(){ $gpls_woo_rfq_cart = gpls_woo_rfq_get_item(gpls_woo_rfq_cart_tran_key() . '_' . 'gpls_woo_rfq_cart'); if(is_array($gpls_woo_rfq_cart)){ $count = count($gpls_woo_r ...

Using Material-UI's <Autocomplete/> component and the getOptionLabel prop to handle an empty string value

Currently, I am working with material-ui autocomplete and passing an array of states to its options property. However, I have encountered an issue with the getOptionLabel method: Material-UI: The `getOptionLabel` method of Autocomplete returned undefined ...

Storing input data in a JavaScript array instead of sending it through an AJAX request

I've been grappling with this issue for quite some time now, and I just can't seem to wrap my head around it. While there are a few similar solutions out there, none of them address my exact problem. Here's the scenario: I have a form where ...

Unable to access the newly created object's properties following the instantiation of a new resource in AngularJS

Currently, I am in the process of developing a new Resource utilizing AngularJS that falls under the category of Person. After successfully creating this resource, my goal is to retrieve the id associated with the new resource from the server. it('sh ...

Unable to utilize a custom function within JQuery

I'm facing an issue with using the function I created. The codes are provided below and I keep encountering a "not a function error." var adjustTransparency = function () { //defining the function if ($(this).css('opacity&apo ...

The routing functionality in Angular4 encounters issues when the `router.navigate()` method is used within the callback of a

I am currently working on implementing Google Sign In within my Angular4 app, but I have run into an unusual issue with routing after using router.navigate() in the Google Sign In callback function. To help illustrate this issue, I have created a sample d ...

Changes to the state will not be reflected until a poll is conducted

Here we have an example of state being initialized and passed down to a child component: const [rowCount, setRowCount] = React.useState<number>(1); <Foo setRowCount={setRowCount} /> Foo: const Foo = (props) => { const { setRowCount } ...