【问题标题】:Angular custom directive to use an if condition in ng-repeatAngular 自定义指令在 ng-repeat 中使用 if 条件
【发布时间】:2019-10-18 18:38:57
【问题描述】:

我正在使用面板来显示本质上是动态的响应。我想使用 2 种不同的颜色来区分面板,即,如果响应的状态为肯定,则面板或面板的标题必须为绿色。如果状态为负,则必须为红色。因为我使用的是自定义指令,所以我无法使用 ng-if。

我的回复中可能存在子数组。如何在我的指令中访问和显示它们?

我该怎么做?

如果状态为正,我希望输出面板为绿色,如果状态为负,我希望输出面板为红色

【问题讨论】:

    标签: html css angularjs angularjs-directive angular-ui-bootstrap


    【解决方案1】:

    您可以使用 ng-class 角度指令应用条件类。

    删除所有应按条件应用的类。将这些类添加为ng-class

    但在您的情况下,您需要在重复语句之前应用该类。在这种情况下,由于它是一个可以包含不同状态的数组,因此面板 div 只能显示一种状态。您可以使用数组的第 0 个元素或其他任何元素。我考虑过第 0 个。

    app.directive('showHide', function() {
        return {
            restrict: 'E',
            scope: {
            items : '=',
    
            },
            template:
            `<div class="panel"
                ng-class="{'panel-danger': items[0].Status === 'Negative', 
                           'panel-default': items[0].Status === 'Positive'}">
                <div class="panel-heading panel-height" ng-repeat="item in items">
                <h3 class = "panel-title">
                    <p class="font">ID: {{item.Id}}</p></h3><br>
                <p class="font">DESCRIPTION: {{item.Desc}}</p><br>
                <p class="font">STATUS: {{item.Status}}</p><br>
                </div></div></div>`,
        };
    });
    

    更新

    为指令创建一个新的模板文件。而不是在指令中包含模板。

    show-hide-directive.js

    app.directive('showHide', function() {
        return {
            restrict: 'E',
            scope: {
                items : '=',
            },
            templateUrl: 'show-hide-directive.html' // <-- Path to the template html file
        };
    });
    

    show-hide-directive.html

    <div class="panel" ng-class="{'panel-danger': items[0].Status === 'Negative', 'panel-default': items[0].Status === 'Positive'}">
        <div class="panel-heading panel-height" ng-repeat="item in items">
            <h3 class = "panel-title">
                <p class="font">ID: {{item.Id}}</p>
            </h3>
            <br>
            <p class="font">DESCRIPTION: {{item.Desc}}</p><br>
            <p class="font">STATUS: {{item.Status}}</p><br>
        </div>
    </div>
    

    【讨论】:

    • 我在使用单引号时遇到语法错误“意外标识符”,即“面板危险”或“否定”。我想这是因为我正在使用自定义指令。应该怎么做才能解决这个问题?还是在自定义指令中使用不同的语法?
    • 不是将模板包装在指令中,而是创建一个新的模板 html 文件。检查更新的答案。
    • 谢谢这工作正常,但颜色差异没有发生。 'panel-default' 只会显示。 panel-danger 没有得到应用
    • 它将采用items 中第一个itemStatus。我猜第一项,即items[0]Status = 'Positive'。如果您想要所有项目的颜色不同,那么您需要在 html 中进行更改。
    • 我也想知道如何从响应中显示子数组
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 2023-04-05
    • 1970-01-01
    • 2013-02-26
    • 2017-02-06
    相关资源
    最近更新 更多