Smart-Table - Preselect a specific row

纵然是瞬间 提交于 2019-12-10 19:03:51

问题


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


回答1:


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');
          }
        });
      }
  }
})



回答2:


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 :)



来源:https://stackoverflow.com/questions/32632384/smart-table-preselect-a-specific-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!