Reputation: 123
I have created some button elements using ng-repeat. Now I need to set opacity of those button elements based on the boolean value in JavaScript without ng-click because the opacity has to be set before any click events.
HTML
<div id="splash_btn_box_ng">
<button id="{{button.buttonId}}" ng-click="setMode(button)" ng-repeat="button in buttons"></button>
</div>
I tried to set opacity in init() like the following,
$scope.buttons.buttonId.style.opacity = 0.3;
and ended up with the following error which means I think button was not created at the time I try to set opacity. So I could not achieve this in init():
TypeError: Cannot set property 'opacity' of undefined
Upvotes: 1
Views: 1875
Reputation: 1533
You can use ng-class
directive to apply a css class conditionally like this :
The toggle opacity button is here for changing the state.
HTML :
<button id="{{button.buttonId}}" ng-class="{'low-opacity': isLow}"
ng-repeat="button in buttons">{{button.buttonId}}</button>
<hr>
<button ng-click="toggleOpacity()">Toggle opcaity</button>
CSS file :
.low-opacity {
opacity: 0.3;
}
Controller :
$scope.isLow = true;
$scope.buttons = [
{
buttonId: 1
},
{
buttonId: 2
}
];
$scope.toggleOpacity = function () {
$scope.isLow = !$scope.isLow;
}
Sample jsfiddle
For more reference :
https://docs.angularjs.org/api/ng/directive/ngClass
Upvotes: 1
Reputation: 590
Did you try ng-style ?
Example
HTML
<button id="{{button.buttonId}}" ng-click="setMode(button)"
ng-repeat="button in buttons" ng-style="myObj">
Welcome
</button>
Controller
$scope.myObj = {
"opacity" : "0.3"
}
Upvotes: 1
Reputation: 44145
Use ng-style
:
<button id="{{button.buttonId}}" ng-style="button" ng-repeat="button in buttons"></button>
Controller:
$scope.button = {
"opacity": "0.3"
}
Upvotes: 1
Reputation: 14689
Don't do direct DOM manipulation like that, use ng-style
or ng-class
directives.
Template:
<button id="{{button.buttonId}}" ng-style="myStyle" ng-repeat="button in buttons"></button>
Controller:
$scope.myStyle = {'opacity': '.3'};
https://docs.angularjs.org/api/ng/directive/ngStyle
https://docs.angularjs.org/api/ng/directive/ngClass
Upvotes: 1