Leveraging ng-selected in AngularJS to effortlessly select multiple options from a collection

Two arrays of objects are causing me some confusion, with one array being a subset of the other:

$scope.taskGroups = [
  {id: 1, name: 'group1', description: 'description1'},
  {id: 2, name: 'group2', description: 'description2'},
  {id: 3, name: 'group3', description: 'description3'}
];

$scope.selectedGroups = [
  {id: 1, name: 'group1', description: 'description1'},
  {id: 2, name: 'group3', description: 'description3'}
];

In an attempt to understand how to use ng-option, I decided to create a function that would determine if an option should be selected in the select list. This decision was based on insights from the documentation:

ngSelected - directive in module ng Sets the selected attribute on the element, if the expression inside ngSelected is truthy.

This led me to develop the following function:

$scope.inSelectedGroups = function(taskGroup) {
  angular.forEach($scope.selectedGroups, function(group) {
    if (taskGroup.id == group.id) {
      return true;
    }
    return false;
  });
};

I then attempted to incorporate this function into the following HTML code:

<select multiple ng-model="selectedGroups" style="width: 100%" size="7">
    <option ng-repeat="taskGroup in taskGroups" value="{{taskGroup.id}}" ng-selected="inSelectedGroups(taskGroup)">{{taskGroup.name}}</option>
</select>

Unfortunately, the full list of taskGroups is displayed, but the selectedTaskGroups are not actually selected...

Could it be that I am heading down the wrong path with this approach?

Answer №1

All taskGroups are displayed in the list, but the selectedTaskGroups remain unselected.

After attempting your suggested solution using the ngSelected attribute without success, I decided to try using the ngOptions instead, and it worked like a charm.

angular.module('app', []).controller('TestController', ['$scope',
  function($scope) {
    $scope.taskGroups = [{
      id: 1,
      name: 'group1',
      description: 'description1'
    }, {
      id: 2,
      name: 'group2',
      description: 'description2'
    }, {
      id: 3,
      name: 'group3',
      description: 'description3'
    }];

    $scope.selectedGroups = [{
      id: 1,
      name: 'group1',
      description: 'description1'
    }, {
      id: 2,
      name: 'group3',
      description: 'description3'
    }];


  }
])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="TestController">
  <select multiple="true" ng-model="selectedGroups" style="width: 100%" ng-options="taskGroup.id as taskGroup.description for taskGroup in taskGroups track by taskGroup.id" size="7">
  </select>
</div>

Answer №2

Make sure to pay close attention, as you are currently returning a Boolean value from a function within the angular.forEach parameter, resulting in nothing being returned from the inSelectedGroups function.

To fix this issue, consider updating your function to:

$scope.inSelectedGroups = function(taskGroup) {
  var flag = false;
  angular.forEach($scope.selectedGroups, function(group) {
    if (taskGroup.id == group.id) {
      flag = true;
      return;
    }
    flag = false;
    return;
  });
  return flag;
};

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

A guide on how to identify the return type of a callback function in TypeScript

Looking at this function I've created function computedLastOf<T>(cb: () => T[]) : Readonly<Ref<T | undefined>> { return computed(() => { const collection = cb(); return collection[collection.length - 1]; }); } Thi ...

optimal method for displaying HTML strings with components in Vue

My website is a Blog/News site featuring posts that contain HTML content stored in the database. In addition to posts, I also want to include elements like sliders which cannot be generated using v-html. I explored Vue's Render Functions to find a so ...

Load images in advance using jQuery to ensure they are cached and retrieve their original sizes before other activities can proceed

When a user clicks on a thumbnail, I aim to display the full-size image in a div. To achieve this, I want to determine the original size of the image based on its source URL before it loads, allowing me to set the appropriate dimensions for the container. ...

I have been working on incorporating a menu item in React, but I keep encountering an error

I am using the MenuItem component to create a dropdown menu in my React project. Despite importing the necessary package, I am encountering an error when running the server. I have searched for solutions but haven't found a definitive me ...

Encountering JSON error when invoking multiple functions

Encountering JSON Error when calling multiple functions Error - Uncaught SyntaxError: Unexpected token ' in JSON at position 0 I've been attempting to call multiple functions in jQuery but keep getting an error. I've tried various soluti ...

Numerous column pictures that occupy the entire browser screen

I am looking to create a grid of clickable images that expand to cover the width of the browser window without any space on either side. Ideally, I would like each image to be 180x180px in size, but if it's easier they can resize based on the browser ...

Azure webhosting blocks the use of AJAX calls

There is a PHP script hosted on my Azure server that returns JSON when accessed through the browser. However, I am having trouble making an AJAX call to this script as none of my requests seem to go through. The issue remains unclear. You can see a failed ...

"Mastering the Geocoder Class: Unleashing the Power of AJAX for Latitude and Longitude Retrie

This JSON array includes a collection of addresses [ { "id": 0, "title": "Coop.Sociale Prassi e Ricerca Onlus", "latitude": 0, "longitude": 0, "address": "Viale Eleonora D'Arborea 12, Roma, IT" }, { "id": 0, "title": "San Lorenzo", "lati ...

Utilize the pipe function to generate a personalized component

I have incorporated a custom pipe in my Angular 2 application to parse and make URLs clickable within messages displayed using an ngFor loop. If the URL links to a YouTube video, I also convert it into embed code. To optimize performance, I am looking to ...

Having trouble with jQuery UI draggable when using jQueryUI version 1.12.1?

Currently, I am diving into the world of jQuery UI. However, I am facing an issue with dragging the boxes that I have created using a combination of HTML and CSS. My setup includes HTML5 and CSS3 alongside jQuery version 1.12.1. Any suggestions or help wou ...

Populate the div with the URL parameter only when another span element is empty after a specified time interval using setTimeout

When displaying a person's name on a page, there are two different methods to consider. It can be extracted from the URL or retrieved from an email form in the CMS used. However, these two approaches sometimes conflict with each other. Currently, I h ...

Connect a series of numerical input fields in Vue.js

One of the tasks I'm working on involves managing a table filled with rows of information. Users can choose multiple rows by checking checkboxes in each row, and I need to keep track of how many rows are selected by updating the totalSelected value. ...

Looking to convert a jQuery function to plain JavaScript code?

Struggling with my homework, I must apologize for any mistakes in my English. My task involves creating a chat using node.js and I found some code snippets on a website "" which I used successfully. The issue now is that the chat relies on old jQuery libr ...

Passing an array from PHP to the DataTables JavaScript library

I am attempting to pass a PHP array to the JS Datatable library for testing purposes. Instead of fetching data from a database, I have simplified my approach. Here is a basic representation of my PHP code: $data_fmt['data'][] = array("TEST"); e ...

Customizing the Class of a jQuery UI ui-autocomplete Combobox Container

Is there a way to customize the ui-autocomplete div by adding a custom class? I have several autocomplete widgets on my webpage, and I need to style their drop-downs differently. Since editing the ui-autocomplete class directly is not an option, I am wor ...

How can we use the Selenium JavascriptExecutor in Java to return an Object from JavaScript?

I've encountered an issue while running a JavaScript file using Java with Selenium in my application. When I execute the JavaScript file with JavascriptExecutor after logging in, I'm only getting a null return instead of a valid one. Below is a ...

Excessive requests to location or history APIs in a brief period of time

Alert: Reached maximum update depth. This issue may arise when a component invokes setState within useEffect without a dependency array, or if any of the dependencies change on each render. const OwnerPage = () => { const onOpen = useAgencyModal((s ...

What is the best way to integrate a JSON response obtained from $http.get in Angular?

When retrieving a JSON using $http.get, I am facing compatibility issues with Angular. To make it compatible, I have to convert it like this: $http.get('/api/v1.0/plans'). success(function(data) { var plans = []; for(var prop ...

Checking localStorage before sending a request with ngResource

Is there a way to check localStorage before ngResource sends a request? I want my resource object to first look in local storage before making a call to the server. Ideally, I'd like to save the initial response from the server in local storage so tha ...

Is there a way to capture the click event of a dynamically generated row within a panel?

Could you please advise on how to capture the click event of a row that is generated within a panel? I have successfully captured events for rows generated on a page using the , but now I need assistance with capturing events from rows within a panel. I c ...