当模式加载并满足特定条件时,默认情况下,我使用ng-checked
来选中复选框。但是,当我对该项执行if ( item.checked)
时,它将返回false。
我正在使用这样的指令。
app.directive( 'toggleButtons', [ function () {
return {
link: function ( scope, element ) {
var toggleButtons = element.find( '.input-add-checkbox' )
function checkState() {
Array.prototype.forEach.call( toggleButtons, function( each ) {
if ( each.checked )
each.parentNode.style.backgroundColor = "#00E0AA"
else if ( !each.checked )
each.parentNode.style.backgroundColor = "transparent"
})
}
Array.prototype.forEach.call( toggleButtons, function (each) {
each.addEventListener( 'click', function () {
checkState()
})
})
checkState()
}
}
}])
我的HTML就像这个
<label for="listen" type="button" class="type-toggle btn btn-green">
<input type="radio" id="listen" name="type" value="listen" ng-checked="{{ currentState == 'app.listen' }}" ng-model="contentParams.type" class="input-add-checkbox" />
<span class="glyphicon glyphicon-headphones"></span>
</label>
为了澄清,该项被正确检查,但JS中的样式在加载指令所在的模板时没有应用。另一个原因可能是它处于AngularUI模式。我也试过按一下暂停键,但没有什么乐趣。
以下是我如何完整使用该指令。
仅使用ng-model
和value
:
<input type="radio" id="listen" name="type"
value="app.init"
ng-model="contentParams.type" class="input-add-checkbox" />
这样,当ng-model
与复选框的值匹配时,将被选中。而不是if(each.checked)
,您应该对照值if(scope.contentParams && each.value === scope.contentParams.type)
进行检查
另一种解决方法是使用ng-attr
,但仅在第一次使用,并且在checkState
fn中,您仍然需要对照value
和scope.contentParams.type
进行检查
ng-attr-checked="{{contentParams.type ==='app.listen'}}
下面是一个工作示例
不要将ng检查和ng模型一起使用。使用ng选中+ng单击,或ng模型+ng更改。
类似的问题:AngularJS:ng模型未绑定到检查复选框