AngularJS conditional ng disabled不会重新启用

AngularJS conditional ng-disabled does not re-enable

本文关键字:新启用 启用 conditional ng disabled AngularJS      更新时间:2023-09-26

给定一个使用ng-disabled="truthy_scope_variable"有条件禁用的文本输入字段,AngularJS在第一次范围变量被伪造时禁用该字段,但在后续更改时不会启用它。因此,该字段将保持禁用状态。我只能假设出了问题,但控制台日志是空的。

truthy scope变量与单选按钮模型绑定,我甚至可以更改$watch,但输入字段的ng-disabled没有按预期工作。我已经手动尝试过调用$apply,但看起来Angular正在触发DOM更改。

在控制器中:

$scope.new_account = true

单选按钮:

<input type="radio" ng-model="new_account" name="register"
 id="radio_new_account" value="true" />
<input type="radio" ng-model="new_account" name="register"
 id="radio_existing_account" value="false" />

条件禁用的输入字段:

<input type="password" ng-disabled="new_account" id="login-password"
 name="password" ng-model="password" />

如果最初设置$scope.new_account = false,则该字段将被禁用,但永远不会重新启用。为什么会发生这种情况?

这是因为HTML属性总是字符串,所以在您的示例中,ngDisabled在两种情况下都在计算字符串("true"或"false")。

为了补救,您应该将模型与ngDisabled:中的字符串值进行比较

ng-disabled="new_account == 'false'"

或者使用复选框,以获得实际的布尔值:

<input type="checkbox" ng-model="existing_account" name="register" id="checkbox_new_account" />
<label for="checkbox_new_account">Is Existing Account</label>
Password:
<input type="password" ng-disabled="existing_account" name="password" ng-model="password" />

这是一个包含两种解决方案的PLNKR。

有一种替代解决方案,只需使用

ng值

 <input type="radio" ng-model="new_account" name="register"
 id="radio_new_account" ng-value="true" />
<input type="radio" ng-model="new_account" name="register"
 id="radio_existing_account" ng-value="false" />
      <input type="password" ng-disabled="new_account" id="login-password"
 name="password" ng-model="password" />

自2016年3月起,绑定值将在Chrome和Firefox中更新ui,即使禁用的ng为true,但在Safari中不为true。在Safari中,当您禁用ng时,ui不会更新,尽管输入元素value属性将具有更新的值(更改后请检查element.value。)

在Safari中,要使用ng-modelng-value指令强制ui更新,必须使用ng readonly而不是ng disabled。