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/.
Written by Blaise Liu
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#