Checkbox doesn't show as checked in UI when checked property set to true in javascript

By : Legion

I have some checkboxes in a table that is being generated in an ng-repeat.

The checkboxes are defined like this:

<input type="checkbox" id="chkView{{::myObj.TeamId}}" 
    ng-click="setViewSelection(myObj.TeamId, this.checked)">

The checkboxes have no ng-model attribute and this was intentional. I wanted to control the checked status of each checkbox directly through javascript.

For some reason the checkbox doesn't respond to it's checked property being updated in javascript. So if I have this statement in javascript:

document.getElementById('chkView27').checked = true;`

It will work programmatically, I can do


And it will print true to the console. But the UI in the browser doesn't reflect that. In the browser the checkbox remains unchecked. I've verified that nothing else is affecting the checked property of the checkboxes after the fact. The UI just doesn't update. Why is this?

EDIT: As per prasad's suggestion I tried wrapping the statement in $scope.$apply like this:

$scope.$apply(function() {
    document.getElementById('chkView27').checked = 'checked';

But this just causes angular to throw an "Action already in progress" error.$rootScope/inprog?p0=$digest

By : Legion


DOM manipulation done in javascript directly wont affect DOM, because it is unknown to angular. If you are doing this in controller directly, it will work. But if you are doing it in plain javascript then you need to use $apply to let angular know that you have made changes in DOM and then angular will update that for you.

By : prasad

Set the checked attribute to the string "checked" as well:

document.getElementById('chkView27').checked = 'checked';

This video can help you solving your question :)
By: admin