Angular Js:单击按钮选择ng-Repeat中的所有按钮而不是一个

时间:2015-07-16 10:41:53

标签: javascript angularjs

我点击了一个按钮(在div块中通过ng-Repeat添加的许多按钮中),所有按钮都会激活"活动"添加了类而不是仅仅点击了那个特定的一个按钮,将所有按钮从蓝色变为红色。 (活动类添加背景:"红色"。)

HTML:

<button ng-repeat="x in diseaselist" class="btn btn-primary" ng-click="clicking(diseaselist)" ng-class="{active:diseaselist.active}">{{x.name}}</button>  

CONTROLLER:

$scope.diseaselist = [{name:"Allergy"},{name:"Arthrites"},{name:"Vomiting"},{name:"Asthma"},{name:"BackPain"}{name:"Malaria"}]

$scope.clicking = function(e){
        e.active = !e.active;
    }

CSS:

button.active{background:red;color:white;}

我只想要点击的按钮有&#34;活动&#34;添加了类,并转为红色(通过CSS)。

2 个答案:

答案 0 :(得分:2)

请查看工作示例:Demo

HTML

  <button ng-repeat="x in diseaselist" class="btn btn-primary" ng-click="clicking($index)" ng-class="{active: active == $index}">{{x.name}}</button>

控制器:

 $scope.name = 'World';
 $scope.diseaselist = [{
    name: "Allergy"
 }, {
    name: "Arthrites"
 }, {
    name: "Vomiting"
 }, {
    name: "Asthma"
 }, {
    name: "BackPain"
 }, {
    name: "Malaria"
 }];

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

答案 1 :(得分:1)

您正在ng-click="clicking(diseaselist)"但是从我看到的diseaselist是所有按钮,您需要使用x