选择UL>使用javascript中的ng-repeat填充的LI元素

时间:2016-09-05 04:36:33

标签: jquery angularjs html-lists

我通过角度ng-repeat填充UL> LI元素。我想在点击ng-repeat之外的按钮时选择其中一个LI。我怎样才能做到这一点?

以下是示例代码。

LI列表



<ul ng-controller="ConstantsController as ctrl" >
 <li ng-repeat="sectionType in sectionTypes">{{sectionType.description}}</li>
</ul>
&#13;
&#13;
&#13;

按钮 - 点击此按钮,需要选择特定的LI。

&#13;
&#13;
<button class="btn btn-primary btn-xs"></button>
&#13;
&#13;
&#13;

例如:

考虑通过ng-repeat填充A,B和C值的LI的例子,点击按钮,我想要选择B。

3 个答案:

答案 0 :(得分:1)

你可以这样做,我已经提供了一个样本,因为你没有提供代码,

单击“应用样式”

在HTML中:

<ul ng-repeat="vote in votes" ng-click="editComment(vote.id)" ng-class="{selected : vote.id === idSelectedVote}">

在控制器中:

$scope.idSelectedVote = null;
$scope.editComment = function(idSelectedVote) {
   $scope.idSelectedVote = idSelectedVote;
   console.log(idSelectedVote);
}

DEMO APP

答案 1 :(得分:0)

您可以在数组ng-class的元素中使用带有isSelected选项的sectionTypes指令。

jsfiddle上的实例。

angular.module('ExampleApp', [])
  .controller('ExampleController', function() {
    var vm = this;
    vm.sectionTypes = [{
      description: "A",
      id: 1,
      isSelected: false
    }, {
      description: "B",
      id: 2,
      isSelected: false
    }, {
      description: "C",
      id: 3,
      isSelected: false
    }];
    vm.setSelected = function(id) {
      //Find particular element in vm.sectionTypes by id
      angular.forEach(vm.sectionTypes, function(item) {
        if (item.id === id)
          item.isSelected = !item.isSelected;
      });
    };
  });
.selected {
  color: red;
  font-style: italic;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
  <div ng-controller="ExampleController as vm">
    <ul>
      <li ng-class="{selected:sectionType.isSelected}" ng-repeat="sectionType in vm.sectionTypes">{{sectionType.description}}</li>
    </ul>
    <button ng-click="vm.setSelected(2)">
      set B Selected
    </button>
    <hr>
    <select ng-model="selectedSection" ng-options="sect as sect.description for sect in vm.sectionTypes">
    </select>
    <button ng-disabled="!selectedSection" ng-click="vm.setSelected(selectedSection.id)">
      set selected by select
    </button>
  </div>
</div>

答案 2 :(得分:-1)

确定。在阅读了一些jquery API之后,我发现以下解决方案更加贴切。

我将 id 分配给UL,然后在javascript中我使用jquery contains 函数来查找LI文本并将其更改为相应地选择

以下是HTML / JSP代码

&#13;
&#13;
<ul ng-controller="ConstantsController as ctrl" id="section-type-list">
                                        <li ng-repeat="sectionType in sectionTypes" ng-click="setSection(sectionType.id, sectionType.description)">{{sectionType.description}}</li>
                                    </ul>
&#13;
&#13;
&#13;

以下是Javascript

&#13;
&#13;
$("#section-type-list li:contains('" + value + "')").addClass('selected');
&#13;
&#13;
&#13;

感谢每一位人士的支持。