Question

I want a button group act as radio buttons like here.

What i want is:

  • The buttons should be disabled by default but ALL the entries should be shown by default.
  • Radio button behaviour.

How can i achieve this with my current code?

My 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>   

My 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;
    };    

} );
Was it helpful?

Solution

Is this along the lines of what you were thinking?

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

Note your button needs to have an ng-class and an ng-click. The ng-click needs to be a function call that sets a scope variable rather than an assignment due to the ng-repeat, which creates child scopes.

<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>

Then your function to select a variable:

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

I wasn't sure if you wanted it to toggle, or not. If not:

$scope.setSelectedTitle = function (value) {
    $scope.selectedTitle = value;
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top