71

I want to set a boolean value to true or false using a select here is my code:

<select class="span9" ng-model="proposal.formalStoryboard">
<option value="false">Not Included</option>
<option value="true">Included</option>
</select>

The value (proposal.formalStoryboard) is set properly to true or false but the change are not reflected on the select box when the value is already assigned.

I tried ng-value="true" and ng-value="false" instead of just value but it's not working as well.

2
  • 1
    ngValue works fine for me (tested on Angular 1.6) <select ng-model="$ctrl.request.invoiced" class="form-control input-lg"> <option ng-value="undefined">All</option> <option ng-value="false">Not Invoiced</option> <option ng-value="true">Invoiced</option> </select> Commented Oct 10, 2017 at 9:24
  • If you are using angular >=1.2.0 see this answer stackoverflow.com/a/47933431/181569 Commented Jan 13, 2022 at 2:22

10 Answers 10

91

EDIT: Commentors have pointed out that my original solution did not work as claimed. I have updated the answer to reflect the correct answer given by others below (I cannot delete an accepted answer).

For Angular 1.0.6, consider this HTML:

<div ng-app="">
  <div ng-controller="MyCntrl">
    <select ng-model="mybool"
            ng-options="o.v as o.n for o in [{ n: 'Not included', v: false }, { n: 'Included', v: true }]">
    </select>
    <p>
        Currently selected: <b>{{ mybool }}</b> opposite: {{ !mybool }}
   </p> 
 </div>
</div>

And this JavaScript:

function MyCntrl($scope) {
    $scope.mybool = true;
}

Here is a working DEMO for Angular 1.0.6 and here is a working DEMO for Angular 1.3.14, which is slightly different.

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

10 Comments

Hi Chris I got that part working, I putted in bold the problem in my question :)
@Jerome Ansia: See comment/answer from sza. You have not posted whatever is causing your problem. This code works.
oh ok give my a few minutes I am gonna check this ;)
@JeromeAnsia, is the code you posted inside an element with ng-repeat or a custom directive? I'm guessing that the <select> exists in a different scope.
This actually doesn't work. I've updated your jsfiddle to show the inverse too: jsfiddle.net/jGfL5/14 This actually sets the value to the string "true" or the string "false" which both evaluate to truthy.
|
59

Just do like this:

<select ng-model="someModel" ng-options="boolToStr(item) for item in [true, false]">
</select>

and define:

$scope.boolToStr = function(arg) {return arg ? 'Included' : 'Not included'};

8 Comments

nice answer, the only one that really seems to address the difficult part of the question
To avoid defining boolToStr, I have ng-options="o.v as o.n for o in [{ n: 'No', v: false }, { n: 'Yes', v: true }]"
Thanks for this answer, by the way! IMO this is the best way to solve this problem.
@Aaron Does this work properly for you? I'm trying it (using Angular 1.3) and although it displays properly, I get a huge error in my stack trace if the var declaration is inlined. If I define the an options array in the controller and loop over it, it works fine. Was wondering if you had the same issues.
@EricB. It works for me inline, with no error printed, and I'm using v1.3.0-beta.2. If you can reproduce the issue in a plunkr I'll see if I can help debug.
|
34

Why not just use this?

<select class="form-control" ng-options="(item?'Included':'Not Included') for item in [true, false]"></select>

1 Comment

Nice. Stores booleans (not Strings) in the model, as desired, and all in one line. There is really no need for a directive or a helper function.
15

If you are using angularjs version >= 1.2.0 you will have access to the directive ng-value

You can use the ng-value on an option element. Your htmls would work like this.

<select ng-model="proposal.formalStoryboard">
    <option ng-value="true">Included</option>
    <option ng-value="false">Not Included</option>
</select>

It also works on radio and checkboxes.

4 Comments

this is the simplest answer that works. Confirmed as of june 2018
easy and simple
That should be accepted, or at least the most up-voted answer!
I appreciate the vote. Looks like ngValue only became available in version 1.2.0 so can understand why it's not the accepted answer
2

I would recommend using a directive for this. As usual, I try to stay away from timeouts and other async operations in preference of a more authoritative and direct control.

directives.directive('boolean', function() {
  return {
    priority: '50',
    require: 'ngModel',
    link: function(_, __, ___, ngModel) {
      ngModel.$parsers.push(function(value) {
        return value == 'true' || value == true;
      });

      ngModel.$formatters.push(function(value) {
        return value && value != 'false' ? 'true' : 'false';
      });
    }
  };
});

The priority is set specifically so that it is done prior to any other directives (that usually don't have a priority set, and defaults to 0)

For example, I use this directive (for a true/false selection) with my selectpicker directive that wraps my select elements in the selectpicker bootstrap plugin.

Edit:

The caveat here, which I forgot to mention, is that your html values need to be string values. What the directive does is translates between the view and the model, keeping the model value in boolean and your view in string format:

%select.selectpicker{ ng: { model: 'modelForm.listed' }, selectpicker: '{ }', boolean: true }
  %option{ value: 'true' } Listed
  %option{ value: 'false' } Unlisted

Comments

2

This will work too. Just force the value to be boolean by putting an angular expression in for the value.

<select class="span9" ng-model="proposal.formalStoryboard">
    <option value="{{false}}" 
           ng-selected="proposal.formalStoryboard === false">
           Not Included
    </option>
    <option value="{{true}}"
            ng-selected="proposal.formalStoryboard === true">
            Included
    </option>
</select>

1 Comment

It works for me, but value of ng model has type string. In my variant after it i have SignalR and it make boolean type for c#, but in many cases it not solve problem.
1

I created sample for you, please check this out.

Is it what you want to use model to drive the ui binding?

<div ng-app ng-controller="Ctrl">
    <select class="span9" ng-model="proposal.formalStoryboard">
        <option value="false">Not Included</option>
        <option value="true">Included</option>
    </select>
    <button ng-click="changeValue();">Click</button>
<div>

function Ctrl($scope) {
    $scope.proposal = {};
    $scope.proposal.formalStoryboard = true;

    $scope.changeValue = function () {
        $scope.proposal.formalStoryboard = !$scope.proposal.formalStoryboard;
        console.log($scope.proposal.formalStoryboard);
    }
}

1 Comment

Your example has a subtle bug. When you select a value with the select it sets the string. As such, if you change the select box to not included, then click the "Click" button the value won't change. This is because it's gone from the string "false" to the value false.
0

I had very little success with this frustrating issue. My solution, while not too elegant since it's an additional line of code, solved it every time. This may not work in every application.

$scope.myObject.myBooleanProperty = $scope.myObject.myBooleanProperty.toString();

Turning it into a "real" string before trying to rebind it to the model displayed on the page allowed it to correctly select the value.

Comments

0

Angular does a strict comparsion between the Value bind to ng-model and the Values in the given Options. The Values given in the initial Question are the Strings "false" and "true". If the Value of ng-model is of Type bool and defined like {"Value":false}, Angulars strict === comparsion between string and bool does never match so the select-box is empty.

The real Problem is- if you select a Value, the Type changed from bool to string ({"Value":false} --> {"Value":"false"})can cause errors if posted back.

The best Solution for both issues for me was the one of Thiago Passos in this Post. (https://stackoverflow.com/a/31636437/6319374)

Comments

-3
<script type='text/javascript'>
function MyCntrl($scope) {<!--from   ww w . j  a  v a 2s.  c om-->
  $scope.mybool = true;
}

</script>
</head>
<body>
  <div ng-app="">
  <div ng-controller="MyCntrl">
    <select ng-model="mybool">
        <option value="false">Not Included</option>
        <option value="true">Included</option>
    </select>
    <p>
    Currently selected: {{ mybool }}
   </p>
 </div>
</div>
</body>
</html>

1 Comment

This is not the solution to the problem and in fact introduces the same problem in the original question.

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.