2016-08-16 229 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>