Angular Selectable Drop-down Menu

I'm facing an issue with using angularjs for dropdown with multiple selection. When I try to include 2 dropdowns in the same form, only one of them gets initialized properly. Here is a sample code snippet http://jsfiddle.net/vUSPu/1221/. Can someone provide guidance on how to display 2 functional dropdowns? Thank you!

<div ng-app="myApp" ng-controller="AppCtrl">    
    <dropdown-multiselect pre-selected="member.roles" model="selected_items" options="roles"></dropdown-multiselect>


    <pre>selected roles = {{selected_items | json}}</pre>
</div>

<div ng-app="myApp2" ng-controller="AppCtrl2">    
    <dropdown-multiselect pre-selected="member.roles" model="selected_items" options="roles"></dropdown-multiselect>


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

app.controller('AppCtrl', function($scope){                     
    $scope.roles = [
          {"id": 1, "name": "Manager", "assignable": true},
          {"id": 2, "name": "Developer", "assignable": true},
          {"id": 3, "name": "Reporter", "assignable": true}
    ];

    $scope.member = {roles: []};
    $scope.selected_items = [];
});

var app2 = angular.module('myApp2', ['app.directives']);

app2.controller('AppCtrl2', function($scope){                     
    $scope.roles = [
          {"id": 1, "name": "Manager", "assignable": true},
          {"id": 2, "name": "Developer", "assignable": true},
          {"id": 3, "name": "Reporter", "assignable": true}
    ];

    $scope.member = {roles: []};
    $scope.selected_items = [];
});

var app_directives = angular.module('app.directives', []);

app_directives.directive('dropdownMultiselect', function(){
   return {
       restrict: 'E',
       scope:{           
            model: '=',
            options: '=',
            pre_selected: '=preSelected'
       },
       template: "<div class='btn-group' data-ng-class='{open: open}'>"+
        "<button class='btn btn-small'>Select</button>"+
                "<button class='btn btn-small dropdown-toggle' data-ng-click='open=!open;openDropdown()'><span class='caret'></span></button>"+
                "<ul class='dropdown-menu' aria-labelledby='dropdownMenu'>" + 
                    "<li><a data-ng-click='selectAll()'><i class='icon-ok-sign'></i>  Check All</a></li>" +
                    "<li><a data-ng-click='deselectAll();'><i class='icon-remove-sign'></i>  Uncheck All</a></li>" +                    
                    "<li class='divider'></li>" +
                    "<li data-ng-repeat='option in options'> <a data-ng-click='setSelectedItem()'>{{option.name}}<span data-ng-class='isChecked(option.id)'></span></a></li>" +                                        
                "</ul>" +
            "</div>" ,
       controller: function($scope){

           $scope.openDropdown = function(){        
                    $scope.selected_items = [];
                    for(var i=0; i<$scope.pre_selected.length; i++){                        $scope.selected_items.push($scope.pre_selected[i].id);
                    }                                        
            };

            $scope.selectAll = function () {
                $scope.model = _.pluck($scope.options, 'id');
                console.log($scope.model);
            };            
            $scope.deselectAll = function() {
                $scope.model=[];
                console.log($scope.model);
            };
            $scope.setSelectedItem = function(){
                var id = this.option.id;
                if (_.contains($scope.model, id)) {
                    $scope.model = _.without($scope.model, id);
                } else {
                    $scope.model.push(id);
                }
                console.log($scope.model);
                return false;
            };
            $scope.isChecked = function (id) {                 
                if (_.contains($scope.model, id)) {
                    return 'icon-ok pull-right';
                }
                return false;
            };                                 
       }
   } 
});

Answer №1

It appears that there is a slight variance between your JSFiddle example and the code you provided. Which one accurately represents your requirements?

Solution in JSFiddle

You seem to have duplicated the ng-app="myApp", resulting in the initialization of the AngularJS app instance for myApp before the second code executes. To address this, you can eliminate the second initialization and nest the second dropdown within the initial (and sole) ng-app scope.

Solution based on the provided code

If you intend to run two distinct applications simultaneously in your document, you must manually begin the process as Angular will only recognize the first one. This script snippet illustrates how you can achieve this:

<script>
  angular.bootstrap(document, ['myApp', 'myApp2']);
</script>

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

The error message "confirm is not a function" occurs when using the link_to function

I'm having trouble implementing a confirm dialogue box on a button, as it's not working and throwing an error: Here is my code snippet: <%= link_to restaurant_survey_path(@restaurant, id: @survey.id), data: { confirm: 'Are you sure?&apo ...

Displaying the format when entering a value with react-number-format

How to Display Format Only After Full Value Inserted in react-number-format I recently implemented the react-number-format package for formatting phone numbers. import { PatternFormat } from 'react-number-format'; <PatternFormat value={v ...

Learn the best practices for incorporating jQuery and other JavaScript libraries in your Angular2 projects

Is it possible to integrate a demo showcasing Bootstrap carousel with CSS3 animations in Angular2 using HTML, CSS, and JS? I have created my own implementation in Plunker with Angular2, but I am facing issues with the animated inner content of the carousel ...

What could be causing the routing to fail in this script?

Currently working on a small project to dive into AngularJS, and I'm facing some challenges with getting the routing to function properly. Despite following numerous tutorials, my code doesn't seem to be working as expected. If anyone could lend ...

Detecting the upcoming click on the document using @HostListener in Angular 4 to dynamically generate a click listener

I'm currently working on a directive that toggles its state when clicked. The desired behavior is for the state to be deactivated if the user clicks anywhere else on the page while it is active. To achieve this, I attempted to use the Renderer2 liste ...

Step by step guide on enabling link routing on a Material UI list item, excluding only one specific button within the list item

I am facing an issue with a component containing ListItem components from material ui. Each ListItem has a button, and the entire listitem should be clickable to route the app somewhere. However, when clicking the delete button, it also routes the app to ...

Ways to append a number to the start or end of an array using JavaScript

Can you help me figure out why the function to order the "s" array from minor to major is adding the number at the end instead of the beginning? The if statement seems to be true (2 < 7 = true) but the logic is not working as expected. Any advice on how to ...

Is there a way to automatically redirect a webpage based on the URL that is entered

Looking for a solution where a page checks a typed link upon loading, such as: www.test.com/myphp.php=10 If it detects a specific number, it should redirect to another link. For example: Upon finding www.test.com/myphp.php=10, it redirects to www. ...

Attempting to extract data from a JSON object within a multidimensional array

Looking at the JSON structure that I need to work with: [ { "result":"OK", "message":"Display", "value":200, "rows":29 } , [ { "personID":1, "img_path":"/1234/", "img ...

Find all elements with the same class and identify the first element among them using jQuery

In my dynamic data structure, I need to filter out all elements with the class name "My_data" and select the first one. In the code below, I am looking to retrieve the first element with the class "My_data". <div class="all_data"> <div class="lis ...

Executing AJAX calls within a forEach loop

I'm facing a challenge with a function that carries out a foreach loop on a list of views and needs to make an AJAX request for each view within the loop. Upon receiving the results in the success callback, it checks if a specific ID is returned and, ...

Disregard any unnecessary lines when it comes to linting and formatting in VSC using EsLint and Prettier

some.JS.Code; //ignore this line from linting etc. ##Software will do some stuff here, but for JS it's an Error## hereGoesJs(); Is there a way to prevent a specific line from being considered during linting and formatting in Visual Studio Code? I h ...

AngularJS: Creating a unique directive for verifying the availability of a username - no duplicates allowed

I have a registration form that includes a username textbox. I would like to implement a custom directive that will check if the entered username already exists in the database. Here is the api implementation: /*get the unique username*/ $app->get(&ap ...

Has the Soundcloud web widget API become obsolete?

I am currently working with the SoundCloud widget API (). My main goal is to retrieve information about the tracks within a set. Unfortunately, it seems like I am only able to utilize the methods widget.getSounds() and widget.getCurrentSound successfully ...

Simulating dynamic route parameters in the Next 13 application directory

I am currently working with Jest and testing library to conduct unit tests on my NextJS application. I am facing difficulties in rendering a page on a dynamic path. Here is the code for my page/component: export default async function MyPage({ params }: { ...

Having some trouble using ionic's `on-swipe-right` method to modify states. Can't seem to get past this error

Apologies for the frustration, I've been trying to resolve this issue for the past few hours. I attempted to navigate to a new state without passing parameters in order to progress, but unfortunately, it hasn't worked out! THE ERROR. Error: C ...

How can I immediately disable a button upon clicking "cancel" on a modal that contains TextFields in React Version 18?

New to React development. Looking for a way to reset a button to its initial disabled state when canceling out of a modal. The scenario is that upon clicking a button, a dialog will appear with an "ADJUST" button that is initially disabled until text is ...

The error message "E/Web Console(8272): Uncaught ReferenceError: functionName is not defined:1" popped up when trying to load web views within a

I'm working on incorporating webviews into a view pager. public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = null; v = inflater.inflate(R.layout.webview_l ...

Closing the Material UI dialog from an inner component

In my application, I have implemented a sign-in dialog using Material UI. However, I have separated the login button into its own component. I am trying to figure out how to close the dialog when the submit button in the SigninForm component is clicked. I ...

Issue with horizontal scrolling in ng-scrollbars occurs when scrolling from right to left

We are currently developing a single page application that supports two languages, one being right to left and the other left to right. For scrolling functionality, we have implemented ng-scrollbars, an Angularjs wrapper for the malihu-custom-scrollbar-pl ...