Problem: Both select lists are moving all items

The code below pertains to a dual select list, as depicted in the image at this link: https://i.sstatic.net/edd21.png

It is functioning as intended. The only issue is that when I click on the last subject in the right-hand side list box (select Subject list), it moves all subjects to the left list box instead of just the selected one.

Any suggestions on how to resolve this?

The code is provided below:

(function () {
    'use strict';

    angular
        .module("eSchoolSystem")
        .directive('multiSelect',['$compile', '$log', multiSelect])

    function multiSelect($compile, $log) {
        return {
            restrict: 'E',
            scope: {
                name: '@',
                selectedModel: '=',
                availableModel: '='
            },
            /*template: '<select id="{{name}}-available" multiple ng-model="availableModel" ng-click="toSelected()" ng-options="a as a.subjectShortName for a in Model.available"></select>\n\n\
                        <select id="{{name}}-selected" ng-click="toAvailable()" multiple ng-model="selectedModel" ng-options="s as s.subjectShortName for s in Model.selected"></select>',
*/
            templateUrl:'app/class/html/dualMultiSelect.html',
            compile: function() {
                return {
                    pre: function($scope, $elem, $attr) {

                        var RefreshSelect = function(original, toFilter) {
                            var filtered = [];
                            angular.forEach(original, function(entity) {
                                var match = false;
                                for (var i = 0; i < toFilter.length; i++) {
                                    if (toFilter[i]["subjectId"] === entity["subjectId"]) {
                                        match = true;
                                        break;
                                    }
                                }
                                if (!match) {
                                    filtered.push(entity);
                                }
                            });
                            return filtered;
                        };

                        var RefreshModel = function() {
                            /*$scope.selectedModel = $scope.Model.selected;*/
                            $scope.selectedModel = angular.copy($scope.Model.selected);
                            /*$scope.availableModel = $scope.Model.available;*/
                            $scope.availableModel = angular.copy($scope.Model.available);
                        };

                        var Init = function() {
                            $scope.Model = {
                                available: $scope.availableModel,
                                selected: $scope.selectedModel
                            };

                            $scope.selectedModel = [];
                            $scope.availableModel = [];

                            $scope.toSelected = function() {

                                $scope.Model.selected = $scope.Model.selected.concat($scope.availableModel);
                                $scope.Model.available = RefreshSelect($scope.Model.available, $scope.availableModel);
                                RefreshModel();
                            };

                            $scope.toAvailable = function() {
                                console.log("in here -x1")
                                console.log("x3-> " + JSON.stringify($scope.selectedModel))
                                $scope.Model.available = $scope.Model.available.concat($scope.selectedModel);
                                $scope.Model.selected = RefreshSelect($scope.Model.selected, $scope.selectedModel);
                                RefreshModel();
                            };

                        };

                        Init();
                    }
                };
            }
        };

    }

}());

Answer №1

Consider revising the RefreshModel function by updating selected values in toSelected and toAvailable:

$scope.toSelected = function() {
    $scope.Model.selected = $scope.Model.selected.concat($scope.availableModel);
    $scope.Model.available = RefreshSelect($scope.Model.available, $scope.availableModel);
    $scope.selectedModel = $scope.availableModel;
    $scope.availableModel = [];
};

$scope.toAvailable = function() {
    $scope.Model.available = $scope.Model.available.concat($scope.selectedModel);
    $scope.Model.selected = RefreshSelect($scope.Model.selected, $scope.selectedModel);
    $scope.selectedModel = [];
    $scope.availableModel = $scope.selectedModel;
};

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

What methods can be used to block the input of non-numeric characters in a text field?

I stumbled upon this particular inquiry. Although, the majority of responses involve intercepting key presses, checking the key code, and halting the event if it does not match an acceptable key code. However, there are some issues with this approach. ...

The module cannot be required as a function for calculating the area of a square

None of the functions I created seem to be working properly. Take a look at this example function: function calculateArea(side) { var area = side * side; return area; } When I attempt to use the module using require, like so: var formulas = require( ...

Identify dead hyperlinks on a webpage with the help of selenium webdriver while steering clear of links that

I have been trying to identify broken links on a webpage by extracting all anchor tags. However, some of the links are dynamically generated through JavaScript. When I attempt to print out the list of all the links, I encounter a StaleElementReferenceExcep ...

What is the best way to choose the unique identifier of an HTML element inside a for loop in a Django template?

I need help selecting an HTML button that is generated within a for loop in a Django template using JavaScript. How can I assign a unique ID to each button and select it correctly in JavaScript? Currently, all buttons have the same ID within the loop, resu ...

Creating a Dynamic Input Validation Range with JQuery

Greetings and thank you for taking the time to review this! :-) The form validation is functioning correctly with required fields, but I am facing a challenge with setting up numeric range validation dynamically for an autocomplete feature. The JQuery val ...

Center-align the text in mui's textfield

What I'm looking for is this: https://i.stack.imgur.com/ny3cy.png Here's what I ended up with: https://i.stack.imgur.com/vh7Lw.png I attempted to apply the style to my input props, but unfortunately, it didn't work. Any suggestions? Than ...

What is the best way to activate a watch upon clicking a button?

Is there a way to use the $watch() method on a button in order to trigger it when the button is pressed? Here is an example of the HTML: <button style="margin-left:10px;" class="btn btn-danger btn-xs"> Re-init tableau ...

Move the cursor to the start of a textarea with the power of jQuery

MyEvent.prototype.sendMessage_ = function(input) { //input is this.find('#mytextarea'); if (input.val().trim() != '') { input.val(''); $('#mytextarea').focus(); } }; //...within the html....// <text ...

Trouble with unproductive downtime in ReactJS and JavaScript

I'm looking for a way to detect idle time and display a dialog automatically after a certain period of inactivity. The dialog should prompt the user to click a button to keep their session active. Currently, when the user clicks the button it doesn&a ...

Retrieve the text content and identification value from each list item

I've found myself in a frustrating situation where I have an unordered list structured like this: var liList = $("#first").find("li"); var append = ""; for(var i =0; i< liList.length; i++){ var item = $(liList); append += "<option value ...

Vue and Vuex retrieve state data from the server in a single request

When loading the History view, data is fetched from the backend server using a Vuex action called in the created() lifecycle hook. This data is then passed to the history table through a computed function named history(), which accesses the history module ...

Utilize IntelliJ's TypeScript/JavaScript feature to extract a method from all instances

I am relatively new to using IntelliJ Idea Ultimate 2020 and I am currently exploring the refactoring functionalities within the software. Is there a way to extract a method from a section of code and apply it to all instances easily and exclusively withi ...

Accessing data from arrays asynchronously using JavaScript

Update I have included actual code below, in addition to the concept provided earlier. Here is the async array access structure I am trying to implement: for (p = 0; p < myList.length ; p++){ for (k = 0; k < RequestList.length; k++){ i ...

Unable to get HTML text input validation with RegEx to function, despite incorporating the required attribute

I am attempting to create dynamically generated text inputs that only allow for digits and an optional decimal point. I have added the required attribute but the inputs are not responding to the RegEx pattern. var howMuch = $("<input>").attr("type", ...

Problems with Ajax functionality in CodePen

Currently working on the Wikipedia Viewer project for freeCodeCamp. I'm encountering an issue with the ajax function as nothing is being logged in the console upon click. The code snippet in question is provided below. Appreciate any help or insight o ...

Tips for maintaining the position of a camera in three.js while also keeping its rotation fixed on the origin

In three.js, I'm looking to dynamically adjust my camera's position while ensuring that its rotation automatically aligns with the world origin. For instance, if the camera is initially set at: camera.position.set(25,25,25) I aim to have the ...

Tips for creating a custom Menu with content overflow in a single direction

What is the goal of this task? I have developed a custom Menu in my application with 8 options. There is a need to dynamically disable certain menu options based on specific conditions (e.g. disabling the last 4 options). When a user hovers over a disable ...

What methods are available for parsing JSON data into an array using JavaScript?

I possess an item. [Object { id=8, question="وصلت المنافذ الجمركية في...طنة حتّى عام 1970م إلى ", choice1="20 منفذًا", more...}, Object { id=22, question="تأسست مطبعة مزون التي تع... الأ ...

retrieve JSON information using jQuery

Hi everyone, I'm trying to figure out how to retrieve JSON data using an AJAX call. I attempted the following method, but it doesn't seem to be working :P First off, I created a JavaScript file where I stored my JSON data: var food = [ ...

Using Promises Across Multiple Files in NodeJs

Initially, I had a file containing a promise that worked perfectly. However, realizing the need to reuse these functions frequently, I decided to create a new file to hold the function and used module.export for universal access. When I log crop_inventory ...