Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling orderBy in AngularJS while editing the list

After applying orderBy in my list of input boxes if i edit any field it starts sorting immediately and i loose focus. I tried to dug in the angular code and found out they have applied something like $watch on the orderBy's attributes therefore whenever the value changes it sorts the list.Is there any way to disable orderBy while editing? I dont want to let the orderBy sort data while editing text. Any help will be appreciated

Here is my plunker

Note: I want to use orderBy & don't need any alternative like sorting the list from any controller itself. I just want the orderBy to sort the list once on page load and then remain quite.

like image 259
I_Debug_Everything Avatar asked Mar 08 '13 09:03

I_Debug_Everything


2 Answers

You could override the directive to change the moment of the update to the moment you wish the reordering. You could also just not use ng-model and rely on a custom directive.

This thread discuss overriding the input directive to change the model update to be triggered by tge blur event. Take a look at the fiddle.

Although you might override the directive, you shouldn't do this, and the best solution, as explained and exemplified by @Liviu T. in the comments below would be to create a custom directive that removes the event keyup binding and adds a blur one. Here is directive code, and here is Liviu's plunker:

app.directive('modelChangeBlur', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
            link: function(scope, elm, attr, ngModelCtrl) {
            if (attr.type === 'radio' || attr.type === 'checkbox') return;

            elm.unbind('input').unbind('keydown').unbind('change');
            elm.bind('blur', function() {
                scope.$apply(function() {
                    ngModelCtrl.$setViewValue(elm.val());
                });         
            });
        }
    };
});
<input type="text" ng-model="variable" model-change-blur/>

Unfortunately, as Angular events are not namespaces, you will have to remove any previously added event.

like image 26
Caio Cunha Avatar answered Sep 18 '22 09:09

Caio Cunha


I was using orderBy on a list that could be re-ordered using angular-sortable, and ran into a similar issue.

My solution was to perform the ordering manually, by calling the orderBy filter inside the controller when the page was initialised, and then calling it subsequently when necessary, for example in a callback function after re-ordering the list.

like image 102
shauneba Avatar answered Sep 19 '22 09:09

shauneba