0

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

1 Answer 1

0

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/

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

1 Comment

Thanks a lot! You really helped in saving a lot of time. :)

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.