2016-08-16 225 views
1

我想要顯示的默認單選按鈕的選擇價值爲3我的代碼如下: -選擇默認值angularjs

<div class="checkbox-group" ng-init="ac.ServiceCode=3"> 

       <input type="radio" ng-model="ac.ServiceCode" id="acuOne" value="1" ng-change='GetAcuityLevel(1)'> 
       <label for="acuityone">1</label> 

       <input type="radio" ng-model="ac.ServiceCode" id="acuTwo" value="2" ng-change='GetAcuityLevel(2)'> 
       <label for="acuitytwo">2</label> 

       <input type="radio" ng-model="ac.ServiceCode" id="acuThree" value="3" ng-change='GetAcuityLevel(3)'> 
       <label for="acuitythree">3</label> 

       <input type="radio" ng-model="ac.ServiceCode" id="acuFour" value="4" ng-change='GetAcuityLevel(4)'> 
       <label for="acuityfour">4</label> 

       <input type="radio" ng-model="ac.ServiceCode" id="acuFive" value="5" ng-change='GetAcuityLevel(5)'> 
       <label for="acuityfive">5</label> 

</div> 

但在這種情況下,它總是顯示3,當我在上面刪除代碼它顯示單選按鈕中正確的選定值。我想如果服務返回一些值(1到5),那麼應該選擇單選按鈕,否則應該選擇默認值3。

+0

顯示您的服務。還有什麼是你指出「當我刪除上面的代碼」?你上面說的代碼的哪一部分? –

+0

我在說ng-init =「ac.ServiceCode = 3」 –

回答

2

這是因爲你有一個ng-init可以幫你。

NG-的init = 「ac.ServiceCode = 3」

通過這種方式,則默認值將始終是3,總是初始化爲該值。

你應該處理ac.ServiceCode是不同的:假設你的服務是$ http.get請求

 $http.get('api/myservice'). 
      success(function(data, status, headers, config) { 
       if(data.valueReturned != null) 
        $scope.ac.ServiceCode = data.valueReturned; 
       else 
        $scope.ac.ServiceCode = 3; 
      }); 
    }; 

換句話說,你應該在你的服務處理您的默認值,而不是在你的HTML。

0

嘗試更換這行:

<div class="checkbox-group" ng-init="ac.ServiceCode=3"> 

有了這個:

<div class="checkbox-group" ng-init="ac.ServiceCode = ac.ServiceCode ? ac.ServiceCode : 3"> 

使用一個ternary operator來檢查值truthy,否則默認爲3

0

,你可以這樣做這個,不使用ng-init,ng-if會解決你的問題。 當服務返回值比適當的值選擇其他3將被選中。

試着改變它,就像$ scope.ac = {};作爲$ scope.ac = {ServiceCode:4} 並觀察行爲。

var app = angular.module('myapp',[]); 
 

 
app.controller('appCtrl',function($scope){ 
 
    
 
    $scope.ac = {}; 
 
    
 
    
 
    
 
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="myapp" ng-controller="appCtrl"> 
 
    <div class="checkbox-group" ng-if="!(ac.ServiceCode)?ac.ServiceCode=3:ac.ServiceCode"> 
 
    <input type="radio" ng-model="ac.ServiceCode" id="acuOne" value="1" ng-change='GetAcuityLevel(1)'> 
 
       <label for="acuityone">1</label> 
 

 
       <input type="radio" ng-model="ac.ServiceCode" id="acuTwo" value="2" ng-change='GetAcuityLevel(2)'> 
 
       <label for="acuitytwo">2</label> 
 

 
       <input type="radio" ng-model="ac.ServiceCode" id="acuThree" value="3" ng-change='GetAcuityLevel(3)'> 
 
       <label for="acuitythree">3</label> 
 

 
       <input type="radio" ng-model="ac.ServiceCode" id="acuFour" value="4" ng-change='GetAcuityLevel(4)'> 
 
       <label for="acuityfour">4</label> 
 

 
       <input type="radio" ng-model="ac.ServiceCode" id="acuFive" value="5" ng-change='GetAcuityLevel(5)'> 
 
       <label for="acuityfive">5</label> 
 

 
    </div> 
 
</div>