Search code examples
angularjsng-style

Combine multiple and contidtional ng-style


I want to combine 2 styles in my ng-style, one of them is conditional style.

ng-style="{'height':height + '%'}"

ng-style="hasScroll !== 0 && {'width': (tableWidth) + 'px'}"

How can I combine both of them without override the width in case the condition is false?

the following isn't good since it's override 'width' property if the condition is falsefalse:

ng-style="{ 'height': height + '%', 'width': hasScroll !== 0 ? (tableWidth) + 'px' : undefined }"

Solution

  • Try this:

    ng-style="hasScroll !== 0 && {'width': (tableWidth) + 'px'} || { 'height': height + '%'}"
    

    Working example:

    var myApp = angular.module('myApp', []);
    
    function MyCtrl($scope) {
         $scope.has = 1;
        
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="myApp" ng-controller="MyCtrl" ng-style=" has != 0 && {'cursor':'pointer','background-color':'blue'} || {'background-color':'blue'} ">
      kick
    </div>