【问题标题】:DRY conformance for this html code此 html 代码的 DRY 一致性
【发布时间】:2015-11-22 06:13:20
【问题描述】:

此代码使用 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('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 &lt; stk.price_alert。如果可能的话,如何修改代码以保持 DRY(不要重复自己)原则?

【问题讨论】:

  • 我认为你不能 DRY html - 这不是编程语言
  • 谢谢。得出声明式语言不能遵循 DRY 的结论是否正确?
  • 我不知道,因为 HTML 不是一种编程语言,所以任何与编程语言的比较都是多余的

标签: javascript html css angularjs dry


【解决方案1】:

听起来您只想消除单个额外的“红色”类声明。为此,请将您的 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 在这一行内嵌套一个额外的表,但我猜你不需要。

【讨论】:

    猜你喜欢
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    • 1970-01-01
    • 2013-12-30
    • 2013-09-09
    • 2020-12-29
    相关资源
    最近更新 更多