Last Updated: February 25, 2016
·
56.24K
· blaiseliu

Use ng-value for ng-model with boolean values

To bind data with radio/checkbox buttons in Angular JS, we use ng-model:

Assuming there is an instructor in $scope:

$scope.instructor = {
    isActive: true,
    course: 'chemistry'
};

To bind instructor.course, which is a string value:

<input type="radio" name="course" value="physics" ng-model="instructor.course"/> Physics
<input type="radio" name="course" value="chemistry" ng-model="instructor.course"/>  Chemistry

But if we do the same with instructor.isActive, a boolean value:

<input type="radio" name="status" value="true" ng-model="instructor.isActive"/> Active
<input type="radio" name="status" value="false" ng-model="instructor.isActive"/>  Inactive

The default value never gets bound.

That is where ng-value is needed. It tells Angular to treat the boolean value as a string.

<input type="radio" name="status" ng-model="instructor.isActive" ng-value="true"/> Active
<input type="radio" name="status" ng-model="instructor.isActive" ng-value="false"/>  Inactive

The working code example is shown in http://jsfiddle.net/blaise_liu/uEZ9r/3/.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside