2016-08-06 60 views
0

我有一個簡單的angularJs示例,其中實際上我必須顯示紅色背景以標記正在檢查的收音機框的infront。但是,我無法在input type =「radio」中選擇selected或isChecked屬性,因此我可以根據它添加CSS。在AngularJs中檢查的收音機旁邊的標籤上添加顏色

HTML

<html> 

<head> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script> 
</head> 

<body ng-app="myApp" ng-controller="myCtrl"> 

<p ng-repeat="x in questions"> 
    <input type="radio" id="{{x.id}}" name="{{x.name}}"><label for="{{x.id}}">{{x.value}}</label> 
</p> 

<script> 
var app = angular.module("myApp", []); 
app.controller('myCtrl',function($scope){ 
    $scope.questions = [ 
     {value:"red",name:"color",id:"1"}, 
     {value:"blue",name:"color",id:"2"}, 
     {value:"yellow",name:"color",id:"3"} 
    ]; 
}); 
</script> 

</body> 
</html> 

enter image description here enter image description here

回答

2

使用:checked僞類只瞄準如果單選按鈕被選中, 然後用+選擇器選擇下面的檢查單選按鈕標籤:

input[type="radio"]:checked + label { 
    background-color: red; 
} 

https://jsfiddle.net/y0fe1d7d/


似乎你想有一個不同的顏色爲每個單選按鈕, 所以我反而建議給予每個單選按鈕時,它的檢查CSS文件中的顏色,給使用內聯樣式(style="..."),然後除去顏色爲未選中狀態(:not(:checked))單選按鈕的背景:

<label for="2" style="background-color: blue;">Blue</label> 

input[type="radio"]:not(:checked) + label { 
    background-color: transparent !important; 
} 

https://jsfiddle.net/y0fe1d7d/1/

0

您可以爲每個元素添加一個ngModel,並利用ngStyle更改labelsbackground-color

就拿這個簡單演示一看:

(function() { 
 
    angular 
 
    .module("myApp", []) 
 
    .controller('myCtrl', myCtrl); 
 

 
    myCtrl.$inject = ['$scope']; 
 

 
    function myCtrl($scope) { 
 
    $scope.questions = [ 
 
     { 
 
      "value":"red", 
 
      "name":"color", 
 
      "id":"1" 
 
     }, 
 
     { 
 
      "value":"blue", 
 
      "name":"color", 
 
      "id":"2" 
 
     }, 
 
     { 
 
      "value":"yellow", 
 
      "name":"color", 
 
      "id":"3" 
 
     } 
 
    ]; 
 
    $scope.radio = {}; 
 
    } 
 
})();
<html> 
 

 
<head> 
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script> 
 
</head> 
 

 
<body ng-app="myApp" ng-controller="myCtrl"> 
 
    <p ng-repeat="x in questions"> 
 
    <input type="radio" id="{{x.id}}" value="{{x.value}}" ng-model="radio.color"> 
 
    <label for="{{x.id}}" ng-bind="x.value" ng-style="{ 'background-color': x.value === radio.color ? x.value : '' }"></label> 
 
    </p> 
 
</body> 
 

 
</html>

相關問題