Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have created a page which contains some text boxes, radio buttons and check boxes. I am using this page to save new data or edit the existing one. I am able to save new data but for editing the data, the page should show some predefined values that it is getting from a variable. I am able to get and set the values for text boxes and radio buttons from that variable. But I am not able to check the check boxes. I have plenty of check boxes so I am using ng-repeat for the values to be displayed on page. I am setting the values of selected check boxes to an array and passing that value to my service layer.

Below are my code snippets:

HTML:

<div id="activityCheckboxList" class="checkboxList">
    <div ng-repeat="activity in activities">
        <label>
                <input type="checkbox" ng-true-value="activity" ng-checked="selection.indexOf(activity) > -1" ng-click="toggleSelection(activity)"/>
                <span>{{activity.activityName}}</span>
            </label>
    </div>
</div>

app.js:

$scope.selection=[];
$scope.getActivities(); //this sets values in $scope.activities which is a     list coming from service layer

    //Get Selected Activities from Check Boxes
    $scope.toggleSelection = function toggleSelection(activity){
        var idx = $scope.selection.indexOf(activity);

        if(idx > -1){
            $scope.selection.splice(idx, 1);
        }
        else{
            $scope.selection.push(activity);
        }
    };

After this, while clicking on submit, I am passing $scope.selection which will contain my activity objects.

For editing the data, I can put the data in selection[]. But how to check the check boxes using that and after that user should be uncheck/check them again. I tried using foreach loop but it didn't help.

Thanks in advance

share|improve this question

As "activity" is an object, indexOf is not right way to find the index. I have made few changes to your code

html

                <input type="checkbox" ng-true-value="activity" 
       ng-checked="checkInSelectionList(activity)" ng-click="toggleSelection(activity)"/>
                <span>{{activity.activityName}}</span>

js

$scope.checkInSelectionList = function (item) {
for(var i=0; i<$scope.selection.length;i++){
    if($scope.selection[i]['ID'] == item['ID']){
    return true;
  }
}
}

You can also use underscore to find the index of an object.

https://jsfiddle.net/nors536b/

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.