javascript - 如何使用 Angular js 有条件地设置特定的类属性?

标签 javascript angularjs ng-class ng-style

我有 1 个 div,我想在其中有条件地设置此类的背景颜色属性。我正在使用boostrap progress bar我只想使用下面的类,因为它包含一些进度条的自定义设置。

下面是我的div:

.statistics .progress-bar {
    background-color: black;
    border-radius: 10px;
    line-height: 20px;
    text-align: center;
    transition: width 0.6s ease 0s;
    width: 0;
}




 <div class="statistics" ng-repeat="item in data">
    <div class="progress-bar" role="progressbar" aria-valuenow="70"
                                    aria-valuemin="0" aria-valuemax="100" ng-style="{'width' : ( item.statistics + '%' )}">
     </div>
  </div>

条件如下:

If statistics > 100
    backgroundcolor=red;
else 
    backgroundcolor=black;

最佳答案

您可以使用简单的表达式来完成

ng-style="<condition> ? { <true-value> } : { <false-value> }"

输出

Updated Output

代码:

<!DOCTYPE html>
    <html ng-app="myApp">

    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
    </head>

    <body ng-controller="myCtrl">

        <div ng-style="item.statistics > 100 ? { 'background-color':'red', 'width': item.statistics + '%' }: { 'background-color':'yellow', 'width': item.statistics + '%'}">
            <h2>$scope.statistics = {{statistics}}</h2>
        </div>

        <div ng-style="item.statistics2 > 100 ? { 'background-color':'red', 'width': item.statistics2 + '%' } : { 'background-color':'yellow', 'width': item.statistics2 + '%'}">
            <h2>$scope.statistics2 = {{statistics2}}</h2>
        </div>

        <script>
            var myApp = angular.module("myApp", []);

            myApp.controller("myCtrl", ['$scope', function($scope) {
                $scope.item = {};
                $scope.item.statistics = 30;
                $scope.item.statistics2 = 101;
            }]);
        </script>
    </body>

    </html>

关于javascript - 如何使用 Angular js 有条件地设置特定的类属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38630071/

相关文章:

javascript - 将一次潜水的完整 html 附加到新的 div

javascript - 点击展开图片

javascript - 即使我的情况按预期发生变化,Angular ngClass 也没有更新我的类

javascript - 使用 ng-include in view 没有显示图形

javascript - 字符串 'properties.dimensions.length' 访问散列 {properties : {dimensions: {length: 23}}}

javascript - 在for循环中完成API获取后如何调用函数?

angularjs - Spring引导应用程序找不到index.html

angularjs - Ionic $state.go 在设备上不起作用

css - Angular 2 中的 ngClass 不在表格中呈现

angularjs - 将 ng-class 与属性/值对表达式一起使用