1

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.

Noah
  • 4,601
  • 9
  • 39
  • 52

2 Answers2

2

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

0

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

Community
  • 1
  • 1
Petr Averyanov
  • 9,327
  • 3
  • 20
  • 38
  • Thanks. But actually after getting rid of `ng-checked`, the result was the same. The check box is checked properly and has the CSS from my `styles.css` file. But the CSS I'm trying to apply with the directive is not applied. – Noah Mar 31 '15 at 19:59