2017-08-03 93 views
0

我在我的項目中的單選按鈕下面實現。我正在使用angularjs技術。Angularjs單選按鈕沒有在json中給出默認值

一旦我在瀏覽器中加載頁面,但值不會進入JSON對象。我已經在標籤中給出了checked =「true」屬性。

當我再次點擊時間json對象與值的單選按鈕。點擊單選按鈕之前

<input type="radio" ng-model="formModel.internationalClient" ng-value="1">Yes 

<input type="radio" ng-model="formModel.internationalClient" ng-value="0" ng-checked="true">No 

JSON對象

{}

後單擊單選按鈕 { 「internationalClient」:0 }

所以,ActuallyI想一旦我的價值正在瀏覽器中加載頁面。

我想要下面的結果,一旦我在瀏覽器上打開我的頁面。 { 「internationalClient」:0 }

+0

使用['ngChecked'(https://docs.angularjs.org/api/ng/directive/ngChecked)與'一起ngModel'沒有任何意義,並可能導致意想不到的結果。您應該在控制器中設置默認值。 –

回答

0

下面是您的c的plnkr酶。 https://plnkr.co/edit/TPbYAr0h3BIXQ1RzuMrv?p=preview

希望這會有所幫助。

<!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"> 
    <script> 
    angular.module('radioExample', []) 
    .controller('ExampleController', ['$scope', function($scope) { 
     $scope.formModel = { 
     internationalClient : 0 
     } 
    }]); 
</script> 
<form name="myForm" ng-controller="ExampleController"> 
    <label> 
    <input type="radio" ng-model="formModel.internationalClient" ng-value="1"> 
    Yes 
    </label><br/> 
    <label> 
    <input type="radio" ng-model="formModel.internationalClient" ng-value="0" ng-checked="true"> 
    No 
    </label><br/> 
    <tt>json = {{formModel}}</tt><br/> 
</form> 
</body> 
</html> 
1

如果這是一個表單模型(不重複),只是初始化控制器:

$scope.formModel.internationalClient = $scope.formModel.internationalClient || 0; 

這對速記:「設置..internationalClient本身,除非..internationalClient爲空「。那樣,如果它是一個國際客戶並且價值被返回,這個操作是冪等的。

如果是在NG-重複的表單等:

<form ng-init="formModel.internationalClient = 0"> 

參考:https://docs.angularjs.org/api/ng/directive/ngInit

+0

這不算是一種壞習慣嗎? –

+1

更新的評論,如果是單一表格,則表示您正確。我處理了很多重複類型的表單,所以它是我的首選。我添加了一個更好的選項作爲第一個目標。 – Brian

+0

第一個選項是一個快捷方式,如果internationalClient不爲空,則將其設置爲0。 – Brian

0

在你的JavaScript文件,您可以設置默認值

$scope.formModel.InternationalClient = 0; 

然後讓你的無線按鈕更改值