gman gman - 1 year ago 89
AngularJS Question

In Angularjs can you sort by selected item using orderByFilter (multiselect listbox)

I'm trying to sort a select by 'selected', then alpha on option. If I use jQuery to put the selected items to the top, it looks great until the user deselects one of the options.

Here is the function I created (which didn't work)

//User clicked a purpose, move it to the top
self.purposeLbChanged = function() {
//self.PurposePvmsObj = orderByFilter(self.PurposePvmsObj , 'DROP_DOWN_VALUE', false); //sort it alpha first...
$("#lbPurpose option:selected").prependTo("#lbPurpose");

Is there a way to do this in angular with

Here is the HTML

<label>Purpose: </label>
<select name="lbPurpose" id="lbPurpose" ng-model="$ctrl.PurposeSelected" multiple ng-change="$ctrl.purposeLbChanged()">
<option ng-repeat="option in $ctrl.PurposePvmsObj" value="{{option.CD}}">{{option.DROP_DOWN_VALUE}}</option>

Clicked on two items
The selected items are at the top

Deselected an item
it doesn't go back to original position

Answer Source

I added a 'position' property to the object to resolve the issue.

        //User clicked a purpose, move it to the top
        self.purposeLbChanged = function() {

            //Clear the position
            angular.forEach(self.PurposePvmsObj, function (eachObj){
                eachObj.Position = 0;

             //Sort the list by DROP_DOWN_VALUE
             self.PurposePvmsObj = orderByFilter(self.PurposePvmsObj , 'DROP_DOWN_VALUE', false);

             //Set the selected values first
             var i = 1;
             angular.forEach(self.PurposeSelected, function (eachString){
                angular.forEach(self.PurposePvmsObj, function (eachObj){
                    if(eachObj.CD.trim() == eachString.trim()){
                        eachObj.Position = 1; //if selected it gets a position of 1.

             //Set the remaining positions
             angular.forEach(self.PurposePvmsObj, function (eachObj){
                if(eachObj.Position == 0){
                    eachObj.Position = i;

             //Sort the list by Postion
             self.PurposePvmsObj = orderByFilter(self.PurposePvmsObj , 'Position', false);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download