菜单中当前选择的项目

时间:2018-08-06 17:47:54

标签: javascript html css angularjs

将项目添加到菜单选择中,使其成为项目组。

HTML代码:

<div class="user1">
<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title">Products</h3>                    
    </div>
    <div class="panel-body">
       <ul id="accordion" class="accordion" >
          <li ng-repeat="(key, categoryType) in categories">

            <div class="link" >{{categoryType.name}}
              <i class="fa fa-chevron-down"></i>
            </div>
            <ul ng-class="{submenu1: categoryType.name == 'Miscellaneous', submenu: categoryType.name != 'Miscellaneous'}">
              <li ng-repeat="item in categoryType[categoryType.name] track by $index"
                  ng-click="getProductDetails(item)">
                <a href="#">{{item.Name}}</a>
              </li>
            </ul>
          </li>                      
        </ul>
    </div>
</div>

谢谢, 罗汉

2 个答案:

答案 0 :(得分:0)

在Angular JS中,这非常简单:

首先,创建一个CSS类来描述选择后的外观:

.selected {
  background-color: yellow;
  border: 3px solid black;
}

然后,只要选择该项,就使用ng-class将此类分配给一个项目。您可以将其放在lia标签上。您的选择:

<li ng-class="{'selected': item.selected}"
    ng-repeat="item in categoryType[categoryType.name] track by $index"
    ng-click="getProductDetails(item)">
  <a href="#">{{item.Name}}</a>
</li>

现在,您需要修改单击项目时所调用的函数,getProductDetails将项目标记为选中。您还需要取消标记所有其他项:

function getProductDetails(item) {
  var items = $scope.categoryType[categoryType.name];
  items.forEach(function(x) {
    x.selected = false;
  });
  item.selected = true;

  //... continue with the rest of your function
}

答案 1 :(得分:0)

比每次单击后遍历列表中的所有项目更有效的方法是仅创建一个范围变量以保存所选项目的索引,并仅将一个类应用于所选索引。

CSS

.selected {
  background-color: #EFEFEF;
}

查看

<li ng-repeat="item in list"
    ng-class="{'selected':selectedItem==$index}"
    ng-click="selectItem($index)">
  {{item.name}}
</li>

CONTROLLER

$scope.selectItem = function(index) {
  $scope.selectedItem = index;
};