Mishty
Mishty

Reputation: 123

How to set the opacity of an element?

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

Answers (4)

Abdelkarim EL AMEL
Abdelkarim EL AMEL

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

Babasile
Babasile

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"
    }

Angularjs ngStyle

Upvotes: 1

Jack Bashford
Jack Bashford

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

mbojko
mbojko

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

Related Questions