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

Inaccurate Guild Member Filtering

Recently, I've been working on creating a unique member counter for my server. The goal is to accurately count the total number of members in the server, excluding bots, and counting only bots as well. However, when I attempt to display these counts i ...

Next.js Page is failing to render React component props

I am currently facing an issue where I need to display data from the props object in a functional component using React. The component structure looks like this: interface TagsComponentProps { tags: Tag[]; } const TagsComponent: FC<TagsComponentPro ...

The state remains unchanged when useState is invoked

I am currently designing a unique restaurant website template. As part of the project, I have implemented a modal box with two arrow buttons to navigate between pages. The issue I am facing is that the value of the pageNumber variable, tracked using useSta ...

How to efficiently close all active Bootstrap modals in an AngularJS application?

I'm dealing with a situation where I've created a modal within another modal. My goal is to use the second modal as a confirmation box to close the first one. However, I'm having trouble getting both modals to close when clicking 'ok&ap ...

Discover distinct and recurring elements

Having two sets of JSON data: vm.userListData = [{ "listId": 1, "permission": "READ" }, { "listId": 2, "permission": "WRITE" }, { "listId": 2, "permission": "READ" }, { "listId": 3, ...

Using Express to request data from Mongo database and only receiving the path

I've been troubleshooting a websocket function that interacts with MongoDB to fetch some data stored in the system using 'get'. const User = require('mongoose'); const express = require('express'); const cal = require(&a ...

React's .map is not compatible with arrays of objects

I want to retrieve all products from my API. Here is the code snippet for fetching products from the API. The following code snippet is functioning properly: const heh = () => { products.map((p) => console.log(p.id)) } The issue ari ...

Switch the text depending on whether the values are 'Y' or 'N'

Just starting out with angular JS and I need help with displaying status in my html page based on predetermined values. The values 'Y' and 'N' come from a service and are stored in an array named ApprovedList. <tr class="row txt- ...

Having trouble with the password strength indicator in React-redux?

Hey there, I'm currently working on implementing a progress strength bar for password validation in React. While I've made progress with the code to check the password regex, I'm struggling to understand how to incorporate the password stren ...

Unable to utilize external JavaScript files in Angular 8

I've been working on integrating an HTML template into my Angular project and for the most part, everything is going smoothly. However, I've encountered an issue where my JS plugins are not loading properly. I have double-checked the file paths i ...

Tips for modifying HTML template code within a Typescript document using Atom

There appears to be a current trend in Angular development where the template code is embedded within the Angular component, usually found in a Typescript or Javascript file. However, when attempting this approach, I noticed that I am missing html syntax ...

Efficiently Loading JavaScript Files in Django for Optimal Website Performance

I have a Django blog app with a Post model that includes a field called body. This field may contain Latex, so I utilize MathJax.js, as well as code snippets, for which I use highlight.js. Sometimes I use both, and other times neither. Is there a way to a ...

When hovering over the bootstrap dropdown, the main dropdown remains a clickable link

How can I create a bootstrap dropdown menu that activates on hover, while still allowing the main button to link to a different page when clicked? Below is the HTML code: <div class="body-wrap"> <div class="container"> <nav class="navbar n ...

How can a directive in Angular UI-Router State be injected with a resolve?

In my current setup, I am utilizing ui-router to dynamically load a directive. The controller is not explicitly defined in the state but rather included within the directive itself. .state('app.main', { url: '/main', ...

Element with absolute position does not expand along with scrollable content (over 100%)

In my popup window, the fade element is supposed to stretch to the full width of the screen. However, when the content exceeds 100% of the browser window height, the element does not extend to the full page height. If I set html, body { height: 100%; over ...

Obtain the ClientID for a particular user control that is within a repeater's bindings

I have a collection of user controls that I am connecting to a repeater. The user control: (Example) "AppProduct" <div> <asp:Button ID="btn_details" runat="server" Text="Trigger" /> <asp:HiddenField ID="pid" ...

Prevent user control postback from occurring when JavaScript is active

I have been on a mission to find a solution to this issue. Hopefully, someone in this community can shed some light on it! I developed a usercontrol that utilizes .NET web controls, but I want to enhance the user experience by avoiding full postbacks. As ...

A guide on managing multiple onClick events within a single React component

Including two custom popups with OK and Cancel buttons. Upon clicking the OK button, a review is composed. This review code is then sent to the server via a post request. Subsequently, the confirmation button reappears along with a popup notifying the user ...

Accessing Cognito using ReactJS and fetching data with specific parameters

I'm currently attempting to retrieve the email of the user who is logged in and use it within my fetch() call. I have successfully obtained the email using getfirstapi() and used it in my form, but I am encountering issues when trying to pass it into ...

Tips on how to dynamically uncheck and check the Nebular checkbox post-rendering

I incorporated a nebular theme checkbox into my Angular 8 App. <nb-checkbox [checked]="enable_checked" (checkedChange)="enable($event)">Enable</nb-checkbox> I am able to update the checkbox using the Boolean variable "enable_checked". Initia ...