Disabling orderBy in AngularJS while editing the list

前端 未结 8 652
情歌与酒
情歌与酒 2021-01-07 23:06

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 fou

8条回答
  •  攒了一身酷
    2021-01-07 23:44

    There's no easy or straightforward way to accomplish what you want, but there are some options. You would have to work without ng-model, and instead use the blur event:

    JS:

    var app = angular.module('myapp', []);
    
    app.controller('MainCtrl', function($scope) {
      $scope.items = [
        { name: 'foo', id: 1, eligible: true },
        { name: 'bar', id: 2, eligible: false },
        { name: 'test', id: 3, eligible: true }
      ];
    
      $scope.onBlur = function($event, item){
        // Here you find the target node in your 'items' array and update it with new value
        _($scope.items).findWhere({id: item.id}).name = $event.currentTarget.value;
      };
    });
    
    app.directive('ngBlur', function($parse) {
      return function ( scope, element, attr ) {
        var fn = $parse(attr.ngBlur);
        element.bind( 'blur', function ( event, arg ) {
          scope.$apply( function(){
            fn(scope, {
              $event : event,
              arg: arg
            });
          });
        });
      };
    });
    

    HTML:

    Plunker.

    But be aware that this would break the two-way binding between the model and the view.

提交回复
热议问题