Smart-Table - Preselect a specific row

2019-07-13 03:16发布

I'm using smart-table and I need to preselect a specific row.

So after loading my list, I loop into it and set the isSelected attribute when I reach the item I want to select:

// Preselect a row
for (var i = 0, len = scope.displayCollection.length; i < len; i += 1) {
    var person = scope.displayCollection[i];
    if (person.firstName === 'Blandine') {
        person.isSelected = true;
        scope.selected = person;
        break;
    }
}

It's working fine, but when I want to select another line, the preselected line is not unselected! I have to click on it to manually unselect it and then be able to select another line correctly.

Here is a JSFiddle explaining the issue: http://jsfiddle.net/6pykn5hu/3/

I tried what's proposed there Smart-Table - Select first row displayed (angularjs) but did not manage to have someting working.

Thanks

2条回答
迷人小祖宗
2楼-- · 2019-07-13 04:09

So I looked through their directive as you can see it calls a function in a parent directive stTable. The row is bound to a click handler...Which calls the ctrl.select() function from stTable this function in turn stores the last selected row. This is your problem because this event does not fire it never sets the last clicked row and thus never looks to remove its class. I rewrote the directive for you so that it would work for what you are trying to achieve but it could pretty easily be improved.

app.directive('prSystem', function () {
  return {
    restrict: 'A',
      require: '^stTable',
      scope: {
        row: '=prSystem'
      },
      link: function (scope, element, attr, ctrl) {
          var mode = attr.stSelectMode || 'single';
          if(scope.row.isSelected) {
              scope.row.isSelected = undefined;
              ctrl.select(scope.row, mode);
          }

        element.bind('click', function () {
          scope.$apply(function () {
            ctrl.select(scope.row, mode);
          });
        });

        scope.$watch('row.isSelected', function (newValue) {
          if (newValue === true) {
            element.addClass('st-selected');
          } else {
            element.removeClass('st-selected');
          }
        });
      }
  }
})
查看更多
放我归山
3楼-- · 2019-07-13 04:13

Finally I found a solution:

No more $watch, but a ng-click on each rows:

<tr st-select-row="row" ng-repeat="row in displayCollection" ng-click="selectRow(row)">

And I manually unselect all row before selecting the clicked one:

scope.selectRow = function (row) {
    for (var i = 0, len = scope.displayCollection.length; i < len; i += 1) {
        scope.displayCollection[i].isSelected = false;
    }
    row.isSelected = true;
    scope.selected = row;
}

Working JSFiddle: http://jsfiddle.net/6pykn5hu/6/

If someone has a better solution, I am open to other suggestions :)

查看更多
登录 后发表回答