我有一个非常简单的表单,其中有"is"和“否”单选按钮。每个单选按钮都绑定(bind)到范围中的同一个项目(我使用的是 AngularJS)。 "is"按钮的值在被选择时设置为 true,“否”按钮的值在被选择时设置为 false。
当我单击"is"按钮一次时,模型和 html 元素都会正确更改。但是,当我单击“否”单选按钮时,模型会正确更改,但 html 元素不会被选中。如果我再次单击“否”单选按钮,html 元素就会更改为正确的选定状态。
下面的示例只是较大 html 页面和 Controller 的一部分,但我保持 Angular 模型结构相同,因为这可能是问题所在。
HTML:
<div ng-app="myApp">
<div ng-conroller="MyController">
<div>
<label>
<input type="radio" name="IsBeingPaid" ng-model="item.isBeingPaid" ng-checked="item.isBeingPaid" value="true"/>
Yes
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="IsBeingPaid" ng-model="item.isBeingPaid" ng-checked="!item.isBeingPaid" value="false"/>
No
</label>
<p>{{item.isBeingPaid}}</p>
</div>
</div>
</div>
Controller :
var app = angular.module('myApp', [
'my.controllers'
]);
var controllers = angular.module('my.controllers', []);
controllers.controller('MyController', function($scope) {
$scope.item = {};
});
我创建了这个 fiddle 来演示这个问题。
http://jsfiddle.net/prajna78/Tdq9n/14/
我错过了什么?这看起来是一件很简单的事情。
最佳答案
您的代码存在一些问题。
首先,在单选按钮元素中使用 ng-value
而不是 value
。这可确保您绑定(bind)的值是 bool 值 (true
),而不是字符串 ("true"
)。另外,您不需要 ng-checked
(ng-model
就足够了)。
<input type="radio" name="IsBeingPaidMinimumWage" ng-model="isBeingPaidMinimumWage" ng-value="true"/>
此外,您正在绑定(bind)到 item.isBeingPaidMinimumWage
,但您的 $scope
变量只是 isBeingPaidMinimumWage
,因此您的初始值 Controller 中的分配不会反射(reflect)在 View 中。
关于javascript - 必须单击单选按钮两次才能使用 AngularJS 更改 html 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24152583/