简体   繁体   English

选择框中的角度、布尔值

[英]Angular, boolean value in a select box

I want to set a boolean value to true or false using a select here is my code:我想使用选择将布尔值设置为 true 或 false 这里是我的代码:

<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.值 (proposal.formalStoryboard) 被正确设置为 true 或 false ,但当该值已分配时,更改不会反映在选择框中。

I tried ng-value="true" and ng-value="false" instead of just value but it's not working as well.我尝试了 ng-value="true" 和 ng-value="false" 而不仅仅是 value,但它不起作用。

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:对于 Angular 1.0.6,请考虑以下 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:还有这个 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.这是一个工作DEMO的角度1.0.6,这里是一个工作DEMO的角度1.3.14,这是稍有不同。

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'};

为什么不直接使用这个?

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

If you are using angularjs version >= 1.2.0 you will have access to the directive ng-value如果您使用的是 angularjs 版本>= 1.2.0您将可以访问指令ng-value

You can use the ng-value on an option element.您可以在选项元素上使用ng-value Your htmls would work like this.你的 html 会像这样工作。

<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.它也适用于收音机和复选框。

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 )优先级是专门设置的,以便在任何其他指令之前完成(通常没有设置优先级,默认为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.例如,我将此指令(用于真/假选择)与我的selectpicker指令一起使用,该指令将我的select元素包装在selectpicker引导插件中。

Edit:编辑:

The caveat here, which I forgot to mention, is that your html values need to be string values.这里需要注意的是,我忘了提及,您的 html 值必须是字符串值。 What the directive does is translates between the view and the model, keeping the model value in boolean and your view in string format:该指令所做的是在视图和模型之间进行转换,将模型值保持为boolean ,将视图保持为string格式:

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

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>

I created sample for you, please check this out.我创建的样本给你,请检查出来。

Is it what you want to use model to drive the ui binding?是你想用model来驱动ui绑定吗?

<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);
    }
}

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.在尝试将其重新绑定到页面上显示的模型之前将其转换为“真实”字符串,可以使其正确选择值。

Angular does a strict comparsion between the Value bind to ng-model and the Values in the given Options. Angular 在绑定到 ng-model 的值和给定选项中的值之间进行了严格的比较。 The Values given in the initial Question are the Strings "false" and "true".初始问题中给出的值是字符串“false”和“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.如果 ng-model 的值是类型 bool 并且定义为 {"Value":false} ,则字符串和 bool 之间的 Angulars 严格 === 比较永远不会匹配,因此选择框为空。

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.真正的问题是 - 如果您选择一个值,则类型从 bool 更改为字符串 ({"Value":false} --> {"Value":"false"}) 如果回发可能会导致错误。

The best Solution for both issues for me was the one of Thiago Passos in this Post.对我来说,这两个问题的最佳解决方案是这篇文章中的 Thiago Passos 之一。 ( https://stackoverflow.com/a/31636437/6319374 ) ( https://stackoverflow.com/a/31636437/6319374 )

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM