如何在ng-repeat中切换当前的div的“活动”类并删除同级div的“活动”类

时间:2019-05-30 07:29:51

标签: html angularjs

我有以下代码。我想点击当前div的“活动”类别,并单击,并删除同级div的“活动”类别。我用ng-repeat

<div class="" ng-repeat="data in people">
<p>{{data.name}}</p>
</div>

控制器

$scope.people=[{
"name" : "john snow"
},
{
"name" : "daenerys"
}]

2 个答案:

答案 0 :(得分:0)

跟踪属性中的活动数据:

$scope.active = null;

实现一项功能,以在每次单击项目时设置该属性:

$scope.setActive = function(data) {
  $scope.active = data;
}

每当单击一个项目时调用该函数:

<div ng-repeat="data in people" ng-click="setActive(data)">

根据div的类别是否与活动类别相匹配来设置:

<div ng-repeat="data in people" ng-click="setActive(data)" ng-class="{ active: data == active }">

Here is a fiddle

答案 1 :(得分:0)

您可以使用ng-class指令来实现。

您需要跟踪最后一个selected值的索引,并使用selected更新setActive()值。点击并从HTML调用setActive(),然后传递对象的索引。

这是一个有效的代码段

var app = angular.module("app", []);

app.controller("myCtrl", ["$scope", ($scope) => {
  $scope.people=[{
    "name" : "john snow"
  },
  {
    "name" : "daenerys"
  },
  {
    "name": "stark"
  }];
  
  $scope.selected = null;

  $scope.setActive = (index) => {
      $scope.selected = index;
  }
}]);
.active {
  background-color: yellow;
  // enter active class css here
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<div ng-app="app" ng-controller="myCtrl">
  <div ng-repeat="data in people">
      <p ng-class="{active: selected === $index}" ng-click="setActive($index)">
        {{data.name}}
      </p>
  </div>
</div>

在此处查看ngClass的文档以获取更多信息:https://docs.angularjs.org/api/ng/directive/ngClass