【问题标题】:Can angular checkbox post a boolean with ng-model, not a string?角度复选框可以使用 ng-model 发布布尔值,而不是字符串吗?
【发布时间】:2016-12-10 05:28:41
【问题描述】:

以下代码在选中时将给出support_enable='true',如果未选中则返回 null。

<form>
  <input type="checkbox" name="support_enable" ng-value="config.support_enable" ng-model="config.support_enable">
</form>

下面的代码在选中时将给出support_enabled='on',如果未选中则返回null。

<form>
  <input type="checkbox" name="support_enable" ng-model="config.support_enable">
</form>

我想知道有没有办法发布一个布尔值?

【问题讨论】:

    标签: angularjs checkbox angular-ngmodel


    【解决方案1】:

    尝试在ng-change上调用函数并根据获取的值更新变量值布尔

    // in your controller
    
    $scope.checkValue = function(value){
      if(value == 'on'){
        config.support_enable = true;
      }
      else 
        config.support_enable = false;
    }
    <form>
      <input type="checkbox" name="support_enable" ng-model="config.support_enable" ng-change="checkValue(config.support_enable)">
    </form>

    【讨论】:

      【解决方案2】:

      在复选框插入隐藏字段之前以旧方式制作

      <form>
      <input type="hidden" name="support_enable" ng-value="config.support_enable" ng-model="config.support_enable">
      <input type="checkbox" name="support_enable" ng-model="config.support_enable">
      </form>
      

      【讨论】:

      • 表单总是发送最后一个元素,所以如果复选框被选中 - 它是复选框,如果不是 - 它是隐藏字段。
      • 我要发布一个布尔值,帖子只是一个字符串。
      • config.support_enable - 把布尔值放在这里
      • 它将发布一个'on'字符串
      猜你喜欢
      • 2021-12-11
      • 2016-02-27
      • 1970-01-01
      • 1970-01-01
      • 2014-08-20
      • 2018-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多