AngularJS条件ng-disabled不会重新启用

Pet*_*ron 38 javascript angularjs angularjs-scope

给定有条件禁用的文本输入字段使用ng-disabled="truthy_scope_variable",AngularJS在第一次伪造范围变量禁用该字段,但在后续更改时不启用它.结果,该字段保持禁用状态.我只能假设出错了,但Console日志是空的.

真实范围变量与单选按钮模型绑定,我甚至$watch可以更改,但输入字段ng-disabled不能按预期工作.我已手动尝试调用$apply,但看起来Angular正在触发DOM更改.

在控制器中:

$scope.new_account = true
Run Code Online (Sandbox Code Playgroud)

单选按钮:

<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" />
Run Code Online (Sandbox Code Playgroud)

有条件禁用的输入字段:

<input type="password" ng-disabled="new_account" id="login-password"
 name="password" ng-model="password" />
Run Code Online (Sandbox Code Playgroud)

如果我最初设置$scope.new_account = false,该字段将被禁用,但永远不会重新启用.为什么会这样?

Ste*_*wie 32

这是因为HTML属性总是字符串,因此在您的示例中,ngDisabled正在评估两种情况下的字符串("true"或"false").

要解决此问题,您应该将模型与ngDisabled中的字符串值进行比较:

ng-disabled="new_account == 'false'"
Run Code Online (Sandbox Code Playgroud)

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

<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" />
Run Code Online (Sandbox Code Playgroud)

这是两个解决方案的PLNKR.


Aja*_*wal 16

有一种替代解决方案可供使用

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" />
Run Code Online (Sandbox Code Playgroud)