0

I have an array of objects with property published which can be true or false. I'm building a filter to be able to display only published or only not published items.

So far the published one works fine like this:

<input 
   type="checkbox" 
   ng-model="search.published" 
   ng-change="search.published = search.published ? true : undefined"> 
Published

And in the ng-repeat it looks like this:

ng-repeat="exhibitor in filterItems = (data | filter: search)"

The problem comes when I try to add another checkbox to display only unpublished items.

I've tried this with a second checkbox:

<input 
   type="checkbox" 
   ng-model="search.published" 
   ng-change="search.published = search.published ? false : undefined"> 
Unpublished

But of course it can't have the same model as the published items one. Also, the checkbox won't get ticked even if I remove the first checkbox.

Any tips on how to work around this?

2
  • 1
    I understand the question is about using checkboxes, but perhaps this could be converted into a UX question... does it make sense to use checkboxes like this? You could try using radio buttons or a select instead, it would save the hassle of workarounds and would be more intuitive Commented Jul 24, 2017 at 19:17
  • 1
    @PatrickBarr select was indeed the right way (: Commented Jul 24, 2017 at 19:31

1 Answer 1

1

Checkboxes automatically assign a true or false value to their ng-model values, so it is unnecessary to use ng-change the way you are.

<input 
   type="checkbox" 
   ng-model="search.published">
Published

When checked, search.published will be true. When unchecked, it will be false. Same goes for the second checkbox, but you should use a different ng-model property.

<input 
   type="checkbox" 
   ng-model="search.unpublished"> 
Unpublished

Next you will need to create a custom filter in your controller:

$scope.myCustomFilter = function(exhibitor) {
    if (exhibitor.published && exhibitor.published === $scope.search.published) {
        return exhibitor;
    } else if (!exhibitor.published && exhibitor.published === $scope.search.unpublished) {
        return exhibitor;
    }
};

You will need you make sure you define $scope.search in your controller.

$scope.search = {
    published: false,
    unpublished: false
};

Now for your ng-repeat:

ng-repeat="exhibitor in filterItems | filter:myCustomFilter"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.