2

Using AngularJS v1.5.0, I am trying to bind a radio input field to a Boolean variable that can be : true, false or null. Using the ng-value directive sets a null value to false.

<input type="radio" ng-model="foo.value" ng-value="true"  ng-change="update()">
<input type="radio" ng-model="foo.value" ng-value="false" ng-change="update()">
<input type="radio" ng-model="foo.value" ng-value="null"  ng-change="update()"> 

Would you have any idea about how this could be done ? Thank you !

2 Answers 2

3

This works for me in 1.4.9. 1.5.0 and 1.6.3

<span ng-init="foo = {value: null}">{{foo}}</span>
<input type="radio" ng-model="foo.value" ng-value="null" ng-checked="foo.value === null" />Null
<input type="radio" ng-model="foo.value" ng-value="true" />True
<input type="radio" ng-model="foo.value" ng-value="false" />False

JsFiddle

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

Comments

2

If you look at the source code for the ngValue directive, you'll notice that it only runs scope.$eval() on values that are true, false or a number.

var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
var ngValueDirective = function() {
  return {
    restrict: 'A',
    priority: 100,
    compile: function(tpl, tplAttr) {
      if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
        return function ngValueConstantLink(scope, elm, attr) {
          attr.$set('value', scope.$eval(attr.ngValue));
        };
      } else {
        return function ngValueLink(scope, elm, attr) {
          scope.$watch(attr.ngValue, function valueWatchAction(value) {
            attr.$set('value', value);
          });
        };
      }
    }
  };
};

To overcome this and include null in that group, you would need to write your own directive, or handle converting the value programmatically when the form gets submitted.

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.