使用ng-value为单选按钮赋值(AngularJS)

4

我是AngularJS的新手.. 我想使用单选按钮进行选择并保存为boolean值。 当我使用ng-value时,保存到数据库的值是null。这是HTML的代码。

<label><input type="radio" ng-model="information" ng-value="TRUE" name="maklumat">Yes</label><br />
<label><input type="radio" ng-model="information" ng-value="FALSE" name="maklumat">False</label>
2个回答

4
问题出在您输入的ng-value值,只需将它们改为小写即可。
<label>
    <input type="radio" ng-model="information" ng-value="true" name="maklumat">Yes
</label>
<br />
<label>
    <input type="radio" ng-model="information" ng-value="false" name="maklumat">False
</label>

示例Fiddle

编辑1

它保存为空的原因是它试图评估未定义的值FALSE


1
此外,最好在控制器中为$scope.information=false分配默认值(对于此情况,因为数据要存入数据库)。 - Nishant123

2
ng-value 期望一个AngularJS表达式,当选中单选框时,它将被用作ngModel的值。
需要注意的是,表达式区分大小写。如果你设置了ng-value="true",那么它会将ng-model的值设置为true;但如果你设置了ng-value="TRUE",它会尝试获取$scope.TRUE,但因为找不到它,ng-model的值会被设置为null
以下是一个例子。

angular.module('radioExample', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.TRUE = "something totally different"
    $scope.specialValue = {
      "id": "12345",
      "value": "green"
    };
  }]);
<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Example - example-radio-input-directive-production</title>
  <script src="//code.angularjs.org/snapshot/angular.min.js"></script>
</head>

<body ng-app="radioExample">

  <form name="myForm" ng-controller="ExampleController">
    <label>
    <input type="radio" ng-model="color.name" ng-value="specialValue">
    SpecialValue
  </label><br/>
    <label>
    <input type="radio" ng-model="color.name" ng-value="true">
    true
  </label><br/>
  <label>
    <input type="radio" ng-model="color.name" ng-value="TRUE">
    TRUE
  </label><br/><br/>
    <tt>color = {{color.name | json}}</tt><br/>
  </form>
  <br><br/><br/> Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
</body>

</html>


实际上,如果他想要一个布尔值,最好使用 ng-value,因为它将该值执行为布尔值而不是字符串。请查看此fiddle以获取示例。此外,在您链接的文档中,它说 如果需要非字符串 ngModel(布尔值、数组等),应使用 ng-value 而不是 value 属性。 - George

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接