2017-04-07 47 views
3

I'am new with angularjs .. 我想使用单选按钮进行选择并保存为boolean值。 当我使用ng-value时,那么保存到数据库中的值是null。这是html的代码。使用ng值为单选按钮(angularjs)

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

回答

0

ng-value预计AngularJS表达到ngModel将被选择的无线时设置。

和表达式是大小写敏感的,如果你设置ng-value="true"它设置你的东西,你必须在ng-modeltrue,但如果你有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>

+0

实际上,如果他想要一个布尔值,最好使用'ng-value',因为它执行的值是布尔值而不是字符串。查看这个[fiddle](http://jsfiddle.net/tur9582o/3/)例子。为了扩展这个以及你已经链接到的文档,说如果你需要一个非字符串ngModel(boolean,array,...),应该使用_ng-value来代替value属性._ – George

+0

@George yes,得到了,更新的答案,谢谢 – tanmay

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

编辑1

它被保存为空是因为它试图评估值FALSE这是不确定的原因。

+1

此外,最好是在控制器中为'$ scope.information = false'分配一个默认值(对于这种情况,因为数据正在进入数据库)。 – Nishant123

相关问题