【问题标题】:Combine multiple and contidtional ng-style结合多重和有条件的 ng 风格
【发布时间】:2016-01-29 00:15:11
【问题描述】:

我想在我的 ng-style 中结合两种样式,其中一种是条件样式。

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

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

如果条件为假,如何在不覆盖宽度的情况下将它们结合起来?

以下不好,因为如果条件为 falsefalse,它会覆盖“宽度”属性:

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

【问题讨论】:

  • 第二个 ng-style 中的 && 不是问号吗?

标签: angularjs ng-style


【解决方案1】:

那么,最好在控制器中处理你的逻辑

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

【讨论】:

    【解决方案2】:

    试试这个:

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

    工作示例:

    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>

    【讨论】:

    • 这不好,因为它总是只应用一种样式
    • 对不起,我的错。答案就在您的评论中。它将始终实现这两者之一。因此,稍作修改,它现在就可以工作了。 :)
    • 我使用了以下内容: ng-style="hasScroll !== 0 ? {'width': (tableWidth) + 'px', 'height': maxHeight} : {'height': maxHeight }"
    【解决方案3】:

    你可以试一试,但读起来不容易:

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

    【讨论】:

    • 如果条件为假则覆盖'width'属性的问题
    【解决方案4】:

    我猜你可以这样做:

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

    【讨论】:

    • 如果条件为假则覆盖'width'属性的问题
    【解决方案5】:

    你可以通过,分隔来添加多个属性

    <div ng-style="{ 'height': height + '%', 'width': hasScroll !== 0 ? (tableWidth) + 'px' : undefined }">
    test data
    </div>
    

    【讨论】:

    • 如果条件为假则覆盖'width'属性的问题
    • 你可以设置一些默认值来代替undefined
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    • 2020-12-19
    • 2017-04-30
    • 2019-08-24
    • 2017-09-23
    • 1970-01-01
    相关资源
    最近更新 更多