简体   繁体   English

当JavaScript中的checked属性设置为true时,复选框未在UI中显示为选中状态

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

I have some checkboxes in a table that is being generated in an ng-repeat . 我在ng-repeat生成的表中有一些复选框。

The checkboxes are defined like this: 复选框的定义如下:

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

The checkboxes have no ng-model attribute and this was intentional. 复选框没有ng-model属性,这是有意的。 I wanted to control the checked status of each checkbox directly through javascript. 我想直接通过javascript控制每个复选框的checked状态。

For some reason the checkbox doesn't respond to it's checked property being updated in javascript. 由于某些原因,该复选框不响应在JavaScript中被更新的checked属性。 So if I have this statement in javascript: 因此,如果我在javascript中有此声明:

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

It will work programmatically, I can do 它会以编程方式工作,我可以

console.log(document.getElementById('chkView27').checked);

And it will print true to the console. 它将true打印到控制台。 But the UI in the browser doesn't reflect that. 但是浏览器中的UI不能反映这一点。 In the browser the checkbox remains unchecked. 在浏览器中,该复选框保持未选中状态。 I've verified that nothing else is affecting the checked property of the checkboxes after the fact. 我已经验证了事实之后,没有其他因素影响复选框的checked属性。 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: 编辑:根据prasad的建议,我尝试将语句包装在$scope.$apply如下所示:

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

But this just causes angular to throw an "Action already in progress" error. 但是,这只会导致angular抛出“动作已进行中”错误。

https://docs.angularjs.org/error/ $rootScope/inprog?p0=$digest https://docs.angularjs.org/error/ $ rootScope / inprog?p0 = $ digest

同样将checked属性设置为字符串“ checked”:

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

DOM manipulation done in javascript directly wont affect DOM, because it is unknown to angular. 用javascript完成的DOM操作不会直接影响DOM,因为它对角度来说是未知的。 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. 但是,如果您使用普通的javascript进行操作,则需要使用$ apply来使angular知道您已在DOM中进行了更改,然后angular将为您更新该内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM