1
votes

Let say I have the following :

  <select class="form-control" name="blah" ng-model="$ctrl.form.blah" ng-options="item.id as item.name group by item.etype | uppercase for item in $ctrl.opts"></select>

Now what I want is to hide/show every GROUP by clicking a group-button i.e. I have button for every group and when I toggle-click it, I want the specified group-options to hide/show in the select-box.

Any way to do this ?


I did it with filter as Yatrix explained, plus I pass the contoller of the component as argument. This way I can access the trigger vars, to decide what exactly to filter.

The only problem I have now is that I was using :

ctrl.form.select_box = ctrl.opts[0].id

I can no longer use that to set default option !! any way to solve that.


this is what I ended up with :

  <select class="form-control" name="blah" ng-model="$ctrl.form.blah" ng-options="item.id as item.name group by item.etype | uppercase for item in $ctrl.opts | blah:$ctrl"></select>

angular.module('myapp').filter('blah', function() {
return function(items, ctrl) {
    rv = [];
    angular.forEach(items, function(item) {
        if (ctrl.blah_f1 && item.etype == 'type1') rv.push(item);
        if (ctrl.blah_f2 && item.etype == 'type2') rv.push(item);
    });
    return rv;
};
});

I know it is not a good idea to directly access the ctrl, but don't see any other way cleanly influencing the filter. The flags are triggered by two buttons which behave both like radio&checkboxes i.e. at least one button has to be on, but is is possible that both are ON. This way the user can decide which "type" of items are in the select-box.

1
Don't pass the controller as an argument in the filter. Keep your concerns separate. A filter should take a list of items and filter it and do nothing more. It shouldn't require knowledge of the controller to work.Yatrix
Can you post your code in a fiddle? It'll be a lot easier to see what you're doing. You're not posting much code here.Yatrix

1 Answers

2
votes

You can use a custom filter. This will filter these items on the front-end. When you toggle it back, it'll be added to the list.

   .filter('myFilter', function () {
      // items = your options
      return function (items) {
        var filtered = [];

        for (var i = 0; i < items.length; i++) {
          var item = items[i];

          // add a property to your model to track what's been removed
          if (!item.removed) {
            filtered.push(item);
          }
        }

        // return all the times that haven't been removed
        return filtered;
      };
    });