1

I am new to AngularJS. I am working on checkboxlist using WebApi and angularJS and need help. Well, there is a checkboxlist where user can select multiple options. I am able to write successful code for this. The selected options are saved into the database. But, on edit, I want those options selected already. How can I achieve this? Thanks.

Here is my checkboxlist:

<div ng-repeat="value in getCheckboxlist">
    <input ichecklist type="checkbox" id="{{value.Id}}" value="{{value.Id}}">
    <span>{{value.Name}}</span>
</div>

Declaration of array:

$scope.selection: [];

and this is how I am getting selected IDs from database on edit:

$scope.selection: selectedValues;

where 'selectedValues' contains json of selected IDs.

3
  • Where your ng-models for these checkboxes? you should do this with ng-checked. Commented Aug 2, 2016 at 11:44
  • I am not using ng-models. Instead, I am triggering ng-click like, ng-click="toggleSelection(value.Id)". This function gets the selected values Ids for me and I save them in db. Commented Aug 2, 2016 at 11:57
  • Ok, you can retrive data from database same way. and add it to value. I will update my answer Commented Aug 2, 2016 at 12:11

2 Answers 2

2

Your are looking for the ngChecked directive from AngularJS

Sets the checked attribute on the element, if the expression inside ngChecked is truthy.

Use it like this

<input id="checkSlave" type="checkbox" ng-checked="expression">

You can replace expression by a call to a function that will verify if this checkbox should be checked or not. The function should return true or false

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

1 Comment

Could your mark it as the answer for the future viewer then please
1

By using ng-checked you can write it as follow

//Angular Controller codes
$scope.Checkboxlist = [{id:1, value:  true, Name: "A"}, {id:2, value: false, Name: "B"}];

//View codes
<div ng-repeat="value in Checkboxlist">
    <input ichecklist type="checkbox" id="{{value.Id}}" ng-checked="Checkboxlist[$index].value">
   <span>{{value.Name}}</span>
</div>

1 Comment

Thanks for the answer, but I had to change the controller in order to get values in json that I didn't want to. So, I used function call in ng-checked, which worked :) Thanks once again :)

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.