使用AngularJS在Bootstrap单选按钮上设置活动类

时间:2015-11-10 15:41:57

标签: javascript html angularjs angular-ui-bootstrap

我尝试使用ng-repeat指令和带复选框行为的按钮在radioGroup中生成radiobuttons。我该怎么做才能正确???

$scope.config = [{
  name: 'First',
  callEvent: 'setValue()'
}, {
  name: 'Second',
  callEvent: 'setValue()'
}, {
  name: 'Third',
  callEvent: 'setValue()'
}];

HTML

<div class="btn-group">
  <label ng-repeat="item in config" class="btn btn-primary classButton"
         ng-click="item.callEvent" ng-model="radioModel" 
         uib-btn-radio="'{{item.name}}'">{{item.name}}
  </label>
</div>

1 个答案:

答案 0 :(得分:1)

要从ng-repeat指令添加的项调用函数,请使用$index作为调用参数。 Bootstrap按钮使用active类来指示选择。使用ng-class指令将active添加到所选按钮的课程中。

<body ng-controller="test">
     <div class="btn-group">
          <label ng-repeat="item in config" 
                 class="btn btn-primary classButton" 
                 ng-class="config[$index].btnClass" 
                 ng-click="setActive($index)">
          {{item.name}}
          </label>
     <br> The active button is -- {{config[activeButton].name}}
     </div>

在您的模型控制器中:

angular.module('app', []).controller('test', function($scope) {
     $scope.config = [{
          name: 'First',
          btnClass: 'active'
     }, {
          name: 'Second',
          btnClass: ""
     }, {
          name: 'Third',
          btnClass: ""
     }];
     $scope.activeButton = 0;
     $scope.setActive = function setActive(index) {
         $scope.activeButton = index;
         for (var i = 0; i < $scope.config.length; i++)
               $scope.config[i].btnClass = "";
         $scope.config[index].btnClass = 'active';
    };
});

Plunker

中的代码