Angular+Bootstrap中的活动按钮状态

Active button states in Angular + Bootstrap

本文关键字:按钮 状态 活动 Angular+Bootstrap      更新时间:2023-09-26

看起来是个简单的问题,但实际上我遇到了麻烦。

点击此处

基本上,我有一个ng重复的按钮,然后点击按钮后会显示一段文本。但是,当我单击一个按钮时,我想从所有其他按钮中隐藏文本块,并从其他按钮中删除活动状态。基本上一次只显示一个按钮块的文本。

看起来很容易,但ng隐藏处理作用域的方式(scope:true)意味着我不能真正查看其他作用域并关闭它们。另一件事是,如果可能的话,我不想更改ng repeat的实际数组这是来自API的数据,我必须发回,如果可以的话,我试图不改变实际的数据结构。

<div class="row" ng-repeat="button in buttons">
    <div class="col-sm-2">
        <button ng-click="showInfo = !showInfo" class="btn btn-primary">{{button.name}}</button>
    </div>
    <div ng-show="showInfo" class="col-sm-3">
        <div class="alert alert-success">{{button.extraInfo}}</div>
    </div>
</div>

和JS

app.controller('MainCtrl', function($scope) {
  $scope.buttons = [
    { name: 'One', extraInfo: 'Extra info for button 1' },
    { name: 'Two', extraInfo: 'Extra info for button 2' },
    { name: 'Three', extraInfo: 'Extra info for button 3' }
  ];
});

我建议创建一个与buttons数组长度相同的新数组,该数组将包含布尔值,以指示项目是否处于活动状态。

我没有登录到plunk,所以这里是你的修改版本。

index.html

  <body ng-controller="MainCtrl as vm">
    <div class="row" ng-repeat="button in buttons track by $index">
      <div class="col-sm-2">
        <button ng-click="vm.setActive($index)" ng-class="vm.isActive[$index] ? 'btn btn-primary' : 'btn'">{{button.name}}</button>
      </div>
      <div ng-show="vm.isActive[$index]" class="col-sm-3">
        <div class="alert alert-success">{{button.extraInfo}}</div>
      </div>
    </div>
  </body>

app.js

app.controller('MainCtrl', function($scope) {
  $scope.buttons = [
    { name: 'One', extraInfo: 'Extra info for button 1' },
    { name: 'Two', extraInfo: 'Extra info for button 2' },
    { name: 'Three', extraInfo: 'Extra info for button 3' }
  ];
  var vm = this;
  vm.isActive =[];
  for(var i=0, len=$scope.buttons.length; i < len; i++){
      vm.isActive[i] = false;
    }
  vm.setActive = function(ind) {
    for(var i=0, len=vm.isActive.length; i < len; i++){
      vm.isActive[i] = i===ind;
    }
  }
});

如果您不想更改实际的数组,请维护另一个对象或数组,该对象或数组将保留每个按钮的显示/隐藏状态的键。

  $scope.showInfo = {};
  $scope.buttons = [
    { name: 'One', extraInfo: 'Extra info for button 1' },
    { name: 'Two', extraInfo: 'Extra info for button 2' },
    { name: 'Three', extraInfo: 'Extra info for button 3' }
  ];
  $scope.changeShowInfo = function(index) {
    for(var prop in $scope.showInfo) {
      $scope.showInfo[prop] = false;
    }
    $scope.showInfo[index] = true;
  };

已解决Plunker

您希望每次有1个按钮处于活动状态,因此您最好使用单选按钮,并使用ng-bind将currentItem保留在作用域中。

HTML:

<body ng-controller="MainCtrl">
    <div name="myForm">
        <div ng-repeat="button in buttons">
            <label>
                <input type="radio" ng-model="$parent.selectedItem" ng-value="button"> {{button.name}}
            </label>
        </div>
    </div>
    <div class="alert alert-success">Extra info: {{selectedItem.extraInfo}}</div>
</body>

不需要更改你的JS。

请参阅此处的Plunker