javascript - 此 html 代码的 DRY 一致性

标签 javascript html css angularjs dry

此代码使用 angularjs ng-table 模块在表格中显示值。

相关的html代码如下所示;

<div ng-controller="ViewCtrl" class="container">
    <table ng-table="tableParams" class="table table-bordered">
        <thead>

        <tr>            
            <th>price_alert</th>
            <th>lastPrice</th>
        </tr>

        <thead>
        <tbody>
        <tr ng-repeat="item in $data">
            <td data-title="'price_alert'" ng-class="{ red: item.lastPrice < stk.price_alert }>
                ${{item.price_alert}}
            </td>
            <td data-title="'lastPrice'" ng-class="{ red: item.lastPrice < stk.price_alert }>
                ${{item.lastPrice}}
            </td>
        </tr>
        </tbody>
        </tbody>
    </table>
</div>

CSS代码;

.red { color: red; }

Controller 代码;

controller('ViewCtrl', ['$scope', '$http', 'moment', 'ngTableParams',
        function ($scope, $http, $timeout, $window, $configuration, $moment, ngTableParams) {
            var tableData = [];
            //Table configuration
            $scope.tableParams = new ngTableParams({
                page: 1,
                count: 100
            },{
                total:tableData.length,
                //Returns the data for rendering
                getData : function($defer,params){
                    var url = 'http://127.0.0.1/list';
                    $http.get(url).then(function(response) {
                        tableData = response.data;
                        $defer.resolve(tableData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                        params.total(tableData.length);
                    });
                }
            });
        }])

在html代码中,重复了这个条件来显示文字颜色ng-class="{ red: item.lastPrice < stk.price_alert .如果可能,如何修改代码以保持 DRY(不要重复自己)原则?

最佳答案

听起来您只想消除单个额外的“红色”类声明。为此,请像这样将您的 ng-class 放在 tr 中:

    <tr ng-repeat="item in $data" ng-class="{ red: item.lastPrice < stk.price_alert }">
        <td data-title="'price_alert'">
            ${{item.price_alert}}
        </td>
        <td data-title="'lastPrice'">
            ${{item.lastPrice}}
        </td>
    </tr>

然后将您的 css 更改为:

.red td { color: red; }

您不能使用此 css 在该行内嵌套额外的表格,但我猜您不需要这样做。

关于javascript - 此 html 代码的 DRY 一致性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33852207/

相关文章:

javascript - 尝试将多个值插入数组(同位素)

javascript - 如何让导航栏顺畅流动?

javascript - 获取 polyfill 在 Edge(或 IE)上不起作用

javascript - 如何使用按钮编辑或输入焦点InputElement

html - 无法获得水平菜单栏

javascript - 统计javascript中数组中元素的出现次数

javascript - 如何编写向 Wix 网站添加计算器的代码?

html - 使用 NODE.JS 和 html5 的低延迟 (50ms) 视频流

javascript - 后网格布局上的随机不同颜色背景

css - 如何锁定网站以适应视口(viewport)内而无法在移动设备上水平滚动