Not getting id in from the selected values in multi-select list box Angular JS

1.1k views Asked by At

I have two list boxes and I have to move items from one list box to another. I was able to achieve this part. Now I want to take the list of all the items in the second list box with the id and save it in the database. I am not getting the ids in the second list box. What is the best way to get all the items in the list box and send it to the controller? Code:

Html:

<div class="control-group">
    <div class="selector">
        <select multiple="multiple" id="SelectLeft" ng-model="TaxId" ng-options="tax.TaxId as tax.TaxName for tax in Taxes"></select>
    </div>
    <input id="MoveRight" type="button" value=" >> " ng-click="MoveTaxes()" />
    <input id="MoveLeft" type="button" value=" << " ng-click="MoveTaxes()" />
    <div class="selector">
        <select id="SelectRight" ng-model="SelectRight" multiple="multiple">
        </select>
    </div>
</div>

JS code is below:

$("#MoveRight,#MoveLeft").click(function (event) {
    var id = $(event.target).attr("id");

    var selectFrom = id == "MoveRight" ? "#SelectLeft" : "#SelectRight";
    var moveTo = id == "MoveRight" ? "#SelectRight" : "#SelectLeft";
    var selectedItems = $(selectFrom + " :selected").toArray();
    $(moveTo).append(selectedItems);
    selectedItems.remove;
});
1

There are 1 answers

0
Siddharth On

Firstly, I dont recommend using jquery in angular. Secondly, you are thinking in jquery when you say "send it to controller".

Now coming to your question -

Define ng-options in second div.

<div class="control-group">
    <div class="selector">
        <select multiple="multiple" id="SelectLeft" ng-model="TaxId" ng-options="tax.TaxId as tax.TaxName for tax in Taxes"></select>
    </div>
    <input id="MoveRight" type="button" value=" >> " ng-click="MoveRight()" />
    <input id="MoveLeft" type="button" value=" << " ng-click="MoveLeft()" />
    <div class="selector">
            <select id="SelectRight" ng-model="SelectRight" ng-options="tax.TaxId as tax.TaxName for tax in TaxesSecond">
            </select>
</div>

Now push the element in second array taxesSecond whenever you move from left to right and remove that element from first array using splice and vice versa.

 $scope.MoveRight = function(){
         $scope.TaxesSecond.push($scope.selectedLeft);
         $scope.Taxes.splice($scope.Taxes.indexOf($scope.selectedLeft),1);
    }

Hope you can write MoveLeft on your own.