Angular UI下拉列表选择

时间:2016-05-06 12:37:30

标签: angularjs

In this plunk我有一个Angular UI下拉列表。有没有办法不在每个<a>元素中重复ng-click?

HTML

<div class="btn-group" uib-dropdown>
  <button id="btn-append-to-body" type="button" class="btn btn-primary" 
      uib-dropdown-toggle>
      {{selection}} <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" uib-dropdown-menu="" role="menu" 
        aria-labelledby="btn-append-to-body">
    <li role="menuitem">
      <a href="#" ng-click="selectItem('1')">The first item</a>
    </li>
    <li role="menuitem">
      <a href="#" ng-click="selectItem('2')">Another item</a>
    </li>
    <li role="menuitem">
      <a href="#" ng-click="selectItem('3')">Yet another item</a>
    </li>
 </ul>

2 个答案:

答案 0 :(得分:2)

this plunker显示如何使用全局 ng-click (传递来源$event)并选择data-value属性作为选定值:

<ul class="dropdown-menu" ng-click="selectItem($event)" uib-dropdown-menu="" role="menu" aria-labelledby="btn-append-to-body">
           <li role="menuitem">
              <a href="#" data-value="1" >The first item</a>
            </li>
            <li role="menuitem">
              <a href="#" data-value="2">Another item</a>
            </li>
            <li role="menuitem">
              <a href="#" data-value="3">Yet another item</a>
            </li>
        </ul>

selectItem()函数,获取所选锚点(ev.target)的数据值属性:

$scope.selectItem = function(ev) {
    $scope.selection = ev.target.dataset.value
};

答案 1 :(得分:0)

如果我理解正确,您可以使用ng-repeat

写下面的内容

控制器代码:

//Your controller logic
$scope.selectItems = ["First Item", "Another Item", "One More Item"]
//some more logic in your controller

HTML查看

<ul class="dropdown-menu" uib-dropdown-menu="" role="menu" aria-labelledby="btn-append-to-body" ng-repeat="(key, value) in selectItems ">
      <li role="menuitem">
        <a href="#" ng-click="selectItem('key')">{{value}}</a>
      </li>
    </ul>

由于我无法访问,因此我无法更新您的plunker