Angular + ui.bootstrap.buttons +无线电过滤器

时间:2013-08-27 03:16:50

标签: twitter-bootstrap angularjs filter radio

我希望按钮组充当here等单选按钮。

我想要的是:

  • 默认情况下应禁用这些按钮,但默认情况下应显示所有条目。
  • 单选按钮行为。

如何使用我当前的代码实现这一目标?

我的HTML:

Filter By Title: 
<div class="btn-group">
<button type="button" ng-repeat="title in titles" class="btn btn-default" ng-model="selected[title]" btn-checkbox>{{title}}</button>
</div>

<table class="table table-bordered table-striped">
      <thead>
        <tr>
          <th>Title</th>
          <th>Text</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="entry in entries | filter:byTitle">
          <td>{{entry.title}}</td>
          <td>{{entry.text}}</td>
        </tr>
      </tbody>
    </table>   

我的JS:

App.controller('MainCtrl', function($scope, $http) {
    $http.get('output/entries.json')
    .then(function(res){
        $scope.entries = res.data;                
    });                      

    $scope.selected = {};
    $scope.titles = ["sometitle","someothertitle","anothertitle"];

    function isChecked(obj){
        var checked = [];
        for(var key in obj){
            if(obj[key])
                checked.push(key);
        }
        return checked;
    };
    $scope.byTitle = function(entry){
        var checked = isChecked($scope.selected);
        return checked.indexOf(entry.title) > -1;
    };    

} );

1 个答案:

答案 0 :(得分:4)

这是否符合您的想法?

http://jsfiddle.net/HB7LU/278/

请注意,您的按钮需要有ng-classng-clickng-click需要是一个函数调用,它设置范围变量而不是由于ng-repeat而设置的赋值,这会创建子范围。

<button 
    type="button" 
    ng-repeat="title in titles" 
    class="btn btn-default" 
    ng-model="selected[title]" 
    btn-checkbox 
    ng-class="{active: title == selectedTitle}" 
    ng-click="setSelectedTitle(title)">{{title}}</button>

然后你的函数选择一个变量:

$scope.setSelectedTitle = function (value) {
    if ($scope.selectedTitle === value) {
        $scope.selectedTitle = undefined;
    } else {
        $scope.selectedTitle = value;
    }
};

我不确定你是否想让它切换。如果不是:

$scope.setSelectedTitle = function (value) {
    $scope.selectedTitle = value;
};