单击“添加和删除类”

时间:2014-01-13 15:46:47

标签: angularjs ng-repeat angularjs-ng-click

我尝试创建一个具有两个状态addadded的点击功能,这两个状态在我的解决方案中都可见,但我只希望一次显示一个状态。到目前为止,我的逻辑是以下列方式构建它。演示我注意到当我点击该项时,该类被激活,我无法删除该类。 Demo

<div ng-repeat= "fav in fav">
   <div ng-click="select(fav)" ng-class="favClass(fav)" class="panel-controls panel-controls__item">
   {{fav}}
</div> 

    var app = angular.module("myApp", []);
  app.controller("favouriteBtn", function ($scope){

     $scope.fav = ['add', 'added'];
     $scope.selected = $scope.fav[0];

     $scope.select = function(fav) {
        $scope.selected = fav;
      };

    $scope.favClass = function(fav){
      return fav === $scope.selected ? 'active' : underfined;
    };
  });

2 个答案:

答案 0 :(得分:0)

只是一个猜测:

ng-class="{active: fav == selected}"

或者如果您只想更改显示按钮:

ng-show="fav == selected" 

ng-show="fav != selected" 

答案 1 :(得分:0)

我会像迈克尔所说的那样做。

在视图上:

<div class="{{selected}}">
  <div ng-show="selected == 'add'">
    <button ng-click="toggleButton()">Button1</button>
  </div>
  <div ng-show="selected == 'added'">
    <button class='disabled'>Button2</button>
  </div>
</div>

在控制器上:

angular.module('myApp').controller('ButtonCtrl',
[
  '$scope',
  function($scope){
    $scope.fav = ['add', 'added'];
    $scope.selected = fav[0];

    $scope.toggleButton = function(){
      $scope.selected = fav[1];
    };
  }
]);