Angularjs - How to change background color using radio button

泪湿孤枕 提交于 2019-12-11 09:41:59

问题


On my page, I have dynamically created radio buttons. I want to change wrapper background color when radio button is selected.

following is my code

<section ng-repeat="list in myList">
  <div class="radioWrapper">
    <input type="radio" name="{{list.category}}" ng-model="list.name">
    <label>{{list.name}} </label>
   </div>
</section>

I want to add "selectedRadioBg" class at the radioWrapper when each radio is selected.

Appreciate any help


回答1:


<section ng-repeat="list in myList">
  <div ng-class="myClass">
    <input type="radio" name="{{list.category}}" ng-model="list.name">
    <label>{{list.name}} </label>
   </div>
</section>

// in controller/link

if($scope.list.name){
  $scope.myClass = {background: #B250C2};
}

See: ngClass

What's happening

You got a ngModel list.name on your radio button. If the radio is checked, it's value evaluates to true

You watch for $scope.list.name to be true, and if so, set an object named myClass to your scope, which contains the styles. This object is bound to your markup:

<div ng-class="myClass">




回答2:


You can make use of the ng-class directive. Documentation can be found here.

This directive allows you to conditionally apply a class based on an expression, in this case the radio button selection.

So, using your example, you can have the following code:

<div class="radioWrapper" ng-class="{'selectedRadioBg': list.name}>
    <input type="radio" name="{{list.category}}" ng-model="list.name">
    <label>{{list.name}} </label>
</div>

list.name acts as a truthy / falsy expression here.




回答3:


<section ng-repeat="list in myList">
    <div class="radioWrapper" ng-class="{'selectedRadioBg': list.name}>
        <input type="radio" name="{{list.category}}" ng-model="list.name">
        <label>{{list.name}} </label>
    </div>
</section>

Replace with

<section ng-repeat="list in myList">
    <div class="radioWrapper" style="background: {{list.name}} none repeat scroll 0% 0%;">
        <input type="radio" name="{{list.category}}" ng-model="list.model">
        <label>{{list.name}} </label>
    </div>
</section>

**Do not put your list.name in ng-model directive.



来源:https://stackoverflow.com/questions/21850899/angularjs-how-to-change-background-color-using-radio-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!