2

Angular v1.5x

There are many other questions that sound similar, but none of them solved my problem, so I'm adding this to try to save someone else time.

This DOESN't Work:

app.controller("Controller", function($scope) {
  $scope.foo.bar = "true"
}

<input type="checkbox" ng-model="foo.bar" />

The two-way binding actually is working. But the checkbox will not be checked on first load.

1 Answer 1

2

This DOES work:

app.controller("Controller", function($scope) {
  $scope.foo.bar = true
}

<input type="checkbox" ng-model="foo.bar" />

Notice that in this version, the value of foo.bar is a boolean. I learned the hard way (after hours of frustration) that ng-model on a checkbox does not work with any truthy value.

Bonus tip:

This is pointed out in many other questions, but it's worth repeating here. Angular is known to behave unpredictably sometimes when you bind directly to primitives instead of properties. Translation: Always include a . in your ng-model.

Good: ng-model="foo.bar"

Bad: ng-model="foobar"

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.