Reputation: 4751
I use ng-checked
to check a checkbox by default when a modal loads and meets a certain condition. However, when I do if ( item.checked)
on that item, it will return false.
I am using a directive like this.
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()
}
}
}])
And my HTML is like this
<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>
To clarify, the item is checked properly, but the style in the JS is not applied on loading the template the directive is in. Another cause might be that it's in an AngularUI modal. I have tried button a timeout on it too, but no joy.
Here is how I use the directive in full.
Upvotes: 1
Views: 589
Reputation: 1885
Only use ng-model
and value
instead:
<input type="radio" id="listen" name="type"
value="app.init"
ng-model="contentParams.type" class="input-add-checkbox" />
That way when the ng-model
matches with your checkbox's value will be selected. And instead of if(each.checked)
you should check against the value if(scope.contentParams && each.value === scope.contentParams.type)
Other way of solve it is to use ng-attr
instead, but only will work the first time, and in the checkState
fn you still will have to check against the value
and the scope.contentParams.type
ng-attr-checked="{{contentParams.type ==='app.listen'}}
Here is a working example
Upvotes: 2
Reputation: 9486
Do not use ng-checked and ng-model together. Use either ng-checked + ng-click, or ng-model + ng-change.
Similar question: AngularJS: ng-model not binding to ng-checked for checkboxes
Upvotes: 0