annabananana7
annabananana7

Reputation: 181

Change label text color with checkbox

I'm using angular-ui-switch on my page. I have on/off labels on either side of the switch. The switch works, but I need to change the color of the text when the toggle switches from on to off and vice versa. The label text should be black when the slider is on that side and blue on the other.

HTML:

<div class="toggle-container">
    <div class="switch-label" ng-class="{enabled:enabled.laww, disabled:!enabled.laww}">Off</div>
        <switch ng-model="enabled.laww" ng-init="enabled.laww=false" class="green unchecked">
            {{ enabled }}
        </switch>
    <div class="switch-label" ng-class="{enabled:!enabled.laww, disabled:enabled.laww}">On</div>
</div>

CSS:

.enabled {
      color: #337ab7;
}
.disabled {
      color: #000;
}

I've been searching and it seems ng-class might be the way to go, but I'm not sure sure how that would fit into my code since I already have class. How should I handle this?

Edit

I added ng-class="{enabled:enabled.laww}" to both labels and that got the labels to change colors when I turn the switch on or off, but they both change to the same color at the same time. I need them to alternate colors for when it's on or off. Do I need to add another class to ng-class?

Edit 2

I figured it out! I had to add a disabled class to ng-class and a not true state in order for the colors to switch. Please see above code for fix.

Upvotes: 0

Views: 3964

Answers (1)

Jodevan
Jodevan

Reputation: 750

Yes, you can achieve this by using ng-class. You can represent a class with an object-like representation:

<div class="{switch-label: enable.laww}">On</div>

Hence the class attribute will be turned on based on the value assigned to it. In this case, the value of enable.laww will be used to activate/deactivate the value of switch-label.

I'm attaching an example in plunker: http://plnkr.co/edit/dxkM8mCkLYTMfuusm09x?p=preview

Javascript:

var myApp = angular.module("myApp", []).
    controller("MyController", function($scope) {
    $scope.myCheckBox = true;
});

In the css:

.greenbg {
     background: lightgreen;
}

In the HTML:

<input type="checkbox" ng-model="myCheckBox">Click me
<div ng-class="{greenbg: myCheckBox}">I'm just some div</div>

You can find more details and examples here: https://docs.angularjs.org/api/ng/directive/ngClass

Upvotes: 1

Related Questions