2

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

5 回答 5

2

Then, Its better to handle your logic in controller

<div ng-style="getStyles()">
test data
</div>

$scope.getStyles = function () {
   var styleObj = {};
   styleObj['height'] = height + '%';
   if ($scope.hasScroll !== 0) {
     styleObj['width'] = tableWidth + 'px';
   }
   return styleObj;
}
于 2016-01-28T14:58:27.317 回答
1

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>

于 2016-01-28T15:13:47.910 回答
0

You can try but it is not easy to read :

ng-style="{ 'height':height + '%', 'width': hasScroll !== 0 ? (tableWidth) + 'px' : undefined }"
于 2016-01-28T14:35:54.917 回答
0

I guess you can do it like this:

ng-style="{ width: hasScroll !== 0 ? tableWidth : 0, height: height }"

于 2016-01-28T14:36:29.177 回答
0

You can add multiple properties by doing with , separation

<div ng-style="{ 'height': height + '%', 'width': hasScroll !== 0 ? (tableWidth) + 'px' : undefined }">
test data
</div>
于 2016-01-28T14:39:45.640 回答