0

I'm trying to do something very simple with checkboxes and Angular 1.x. I want to pre-select some checkboxes on an edit page and then after some selections are made to save the data to a backend.

I have created this demo:

http://jsfiddle.net/roL38ctk/3/

I'm able to pre-select the checkboxes but I struggle to see how the selected items or of any use and could ever be saved to a database, for example after checking and un-checking the options my ng-model might look like this:

{"300":false,"400":true}

When saving I need to know the ids which have been selected, I have no need or desire to know the state of the checkboxes. Something like:

{300,305,310}

To me it seems that Angular doesn't handle checkboxes very well without having to hack objects together to extract and massage the data ready for saving.

As a guide I have used http://embed.plnkr.co/g0NMG4rmF4uwzoG2uZhf/preview which I believe is reputable source and claims to be the Angular way? I'm disbelieving that something some elementary can be so taxing when a PHP framework manages this effortlessly. Where am I going wrong?

2
  • why using a new array ? why don't you set the "checked" property in each of your categories array and bind the checkbox to that ? Something like this forked fiddle from yours Commented Apr 3, 2019 at 0:01
  • @Gonzalo.- Thanks but although your fork gives me the ids I can't save the object to my database,without first looping over the object to extract the data. Is it not possible to just have an object of ids? Commented Apr 3, 2019 at 6:54

1 Answer 1

4

Just put this code in your submit function. You will get values as your expectation:

    var arryList=[];
        angular.forEach($scope.selection.ids, function (val, key) {
                        if(val==true){
                    var vd = key;
                    arryList.push(vd);
                    }
                });
 alert(arryList);

Or you can use angularjs material checkboxs Check here.

It's third demo already satisfy your requirement.

Sign up to request clarification or add additional context in comments.

2 Comments

I marked this answer as the solution because a third part library is required, although I chose to use Checklist-model as it is a bit lighter- one file required. Angular Material seemed to me to be a little heavy with 4 files required and gave a horrible ui
If you used angularjs ui routing then ui would not heavy because all library load just once to whole session.

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.