1

所以我有一个项目表,当我单击一行时,该行被选中。我在这里上传了一个演示:http: //plnkr.co/edit/m0TgTAQqITDIibMz7C4w ?p=preview

问题是如何让我能够一次选择一个项目并取消选择前一个活动项目?我对编辑和删除菜单也有问题,因为它们必须放置在控制器区域之外,因此如何仅在选择项目时显示它。

<nav class="navbar navbar-default" role="navigation">
  <ul ng-show="true" class="nav navbar-nav">
    <li><a href="#">Remove</a></li>
    <li><a href="#">Edit</a></li>
  </ul>
</nav>
<table ng-controller="PersonController" class="table">
 <tr>
   <th>Name</th>
   <th>Age</th>
 </tr>
  <tr ng-repeat="person in people" ng-click="selectPerson(person)" ng-class="{active: person.selected }">
    <td>{{ person.name }}</td>
    <td>{{ person.age }}</td>
  </tr>
</table>

<script>
function PersonController($scope) {
  $scope.people = [
    { name: 'adam', age: 240 },
    { name: 'steve', age: 30 }
  ];

  $scope.selectPerson = function(person) {
    person.selected = true;
  };
}
</script>
4

1 回答 1

2

对于您关于多项选择的第一个问题,您可以在调用 selectPerson 时缓存范围内的最后一个选定项目,然后在下次调用 selectPerson 时通过说 lastPerson.selected = false 取消选择它。例子:

function PersonController($scope) {
  $scope.people = [
    { name: 'adam', age: 240 },
    { name: 'steve', age: 30 }
  ];

  $scope.lastPerson = null;
  $scope.selectPerson = function(person) {
    person.selected = true;
    if($scope.lastPerson) {
      $scope.lastPerson.selected = false;
    }
    $scope.lastPerson = null;
    $scope.lastPerson = person;
  };
}

我建议将编辑/删除菜单移动到服务中,然后您可以从任何控制器全局访问它并更改它的行为。例子:

<!-- HTML -->
<div ng-controller="MenuCtrl" class="menu-parent">
  <div ng-show="!isCollapsed" class="menu-container">
    <!-- menu goes here -->
  </div>
</div>

// controller
function MenuCtrl($scope, menuService) {
    $scope.isCollapsed = true;

    $scope.menuService = menuService;
    $scope.$watch('menuService.menuCollapsed', function(newVal, oldVal, scope) {
        $scope.isCollapsed = menuService.menuCollapsed;
    });
}

// service
angular.service('menuService', function () {
    return {
      menuCollapsed: false
    };
  });

// example usage in any controller
function RandomCtrl($scope, menuService) {
  $scope.randomEvent = function() {
    menuService.menuCollapsed = true;
  }
}

如果您愿意,我很乐意帮助您住在这里:https ://www.sudonow.com/session/52699424ea4032693f000071

于 2013-10-24T21:40:54.027 回答