0

So I am new to AngularJS and I am looking to create good code because my application is going to scale.

Now, I have a list of competences that I'll get from my API, and then I need to make a list of them with a checkbox, so the user will select/deselect from the list, and then submit that form.

So how can I achieve that? What should be in the ng-model of every checkbox? Should I create a form with all the values in set in false?

Here's my controller code now:

function Controller(Competence) {

    var vm = this;

    vm.competences = [];

    function initController() {
        Competence.getAll()
            .then(function(data) {
                vm.competences = data;
        });
    }

    initController();

}

And here's my view code:

<table>
    <thead>
        <tr>
            <th width="90%">Competence</th>
            <th width="10%">Select</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="competence in vm.competences">
            <td>{{ competence.name }}</td>
            <td><input type="checkbox"></td>
        </tr>
    </tbody>
</table>

1 Answer 1

1

So far your code looks good. To set checkbox values, just add ng-model="competence.selected" to each checkbox input element like this:

<input type="checkbox" ng-model="competence.selected">

Now when you select the checkbox it will set competence.selected to true, and when you deselect it the value will be false.

Form Submission

Wrap your table in a <form> with an ng-submit attribute, and create a function to submit the form:

<form ng-controller="MyCtrl as vm" ng-submit="vm.submitForm()">

  <!-- your table here ... -->

<input type="submit" value="Submit">
</form>

In your controller:

vm.submitForm = function(){

    vm.competences.forEach(function(competence){

        if(competence.selected) console.log(competence);

        // or POST the competences using the $http service ...

    })

  }

See JSFiddle also: Checkbox Demo

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

1 Comment

Sounds really good. Didn't realize that I could add the "selected" property to the javascript object at the view. Thought that I needed to add in the controller and then yes it would be accesible by the view. Thanks a lot!

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.