将绿色背景添加到包含所选无线电输入的标签

时间:2018-01-17 23:47:18

标签: angularjs

我是棱角分明的新人。我希望通过单击所选的无线电输入,标签变为绿色。我该怎么办?

<div ng-app="myApp">
    <div ng-controller="myController">
        <div>Which one?</div>
        <label class="radio" ng-repeat="eval in evaluators">
            <input type="radio" ng-model="cell.evaluator" name="evaluatorOptions" value="{{eval.name}}">{{eval.name}}
        </label>
            <hr />
        <div>You picked: {{cell.evaluator}}</div>
    </div>
</div>

var app = angular.module('myApp', []);
app.controller('myController', function ($scope) {
    $scope.cell = {
        evaluator: "Guava2"
    };
    $scope.evaluators = [{
        name: "Guava1"
    }, {
        name: "Guava2"
    }];


});

http://jsfiddle.net/77axwybr/

1 个答案:

答案 0 :(得分:1)

您可以使用ng-class使用范围上的方法动态设置标签的类,该方法使用ng-model中的设置检查当前值。

<style>
 .selected {
  background: green;
 }
</style>

<div ng-app="myApp">
    <div ng-controller="myController">
        <div>Which one?</div>
        <label ng-class="{selected: isSelected(eval.name) }" class="radio" ng-repeat="eval in evaluators">
            <input type="radio" ng-model="cell.evaluator" name="evaluatorOptions" value="{{eval.name}}">{{eval.name}}
        </label>
            <hr />
        <div>You picked: {{cell.evaluator}}</div>
    </div>
</div>

var app = angular.module('myApp', []);
app.controller('myController', function ($scope) {
    $scope.isSelected = (name) => $scope.cell.evaluator === name;

    $scope.cell = {
        evaluator: "Guava2"
    };
    $scope.evaluators = [{
        name: "Guava1"
    }, {
        name: "Guava2"
    }];
});

http://jsfiddle.net/vsdvcepn/