【问题标题】:apply CSS class on HTML element inside ng-repeat based on condition [duplicate]根据条件在 ng-repeat 内的 HTML 元素上应用 CSS 类 [重复]
【发布时间】:2016-12-28 09:00:50
【问题描述】:

我正在尝试根据 active 变量使 HTML 标题处于活动/非活动状态。但是要在点击标题时设置active 标志,我使用的是ng-repeat 指令的$index 变量:

<div ng-init="active = 1">
  <h4 ng-repeat="(key, val) in vm.headings" ng-click="active = $index" ng-class="{'active': active === $index}">
{{key}}
</h4>
</div>

标题对象:

vm.headings = {
    "HEADING_1": "CONTENT",
    "HEADING_2": "CONTENT",
    "HEADING_3": "CONTENT"
};

第一次加载时,其中一个标题按设置显示为“活动”。但是在随后的点击中,它并没有给出预期的结果。所有标题在单击它们时都会变为活动状态。 Here is the fiddle.

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    试试这个:

    <h4 ng-repeat="(key, val) in vm.headings" ng-click="selectH($index)" ng-class="{'active': active === $index}">
    

    在控制器中:

    $scope.selectH= function(index) {
       $scope.active = index; 
    };
    

    希望这会奏效。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 2014-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多