在 AngularJS 模式模板中显示更多和隐藏详细信息

Show more and Hide details in an AngularJS modal template

我有一个 AngularJS 模态模板,我可以在其中投射来自范围的响应。模板看起来像这样:

<div class="modal-body" id="modal-body">
<uib-accordion close-others="true">
    <div uib-accordion-group class="mt-1" ng-repeat="x in data.details" heading="{{data.displayName}}">
        <pre>{{ x|json:4 }}</pre>
    </div>
</uib-accordion>

我想先显示一个 table 最重要的字段 'x' 然后,在点击按钮的地方给出一个“showMore”字段,我们将显示完整 JSON .此处的按钮用作显示重要详细信息 (table) 或完整详细信息 (Json 响应) 的开关 我遵循的是一种较少 Angular 的方式,但使用的是 Javascript 和 HTML。下面这个实现:

<div class="modal-body" id="modal-body">
<uib-accordion close-others="true">
    <div uib-accordion-group class="mt-1" ng-repeat="x in data.details" heading="{{data.displayName}}">
        <span id="dots"> <table>..</table> </span>
        <span id="more"> <pre>{{ x|json:4 }}</pre> </span>
        <button onclick="myFunction()" id="myBtn">Read more</button>
    </div>
</uib-accordion>

<script type="text/javascript">
    function myFunction() {
        var dots = document.getElementById("dots");
        var moreText = document.getElementById("more");
        var btnText = document.getElementById("myBtn");

        if (dots.style.display === "none") {
            dots.style.display = "inline";
            btnText.innerHTML = "Read more";
            moreText.style.display = "none";
        } else {
            dots.style.display = "none";
            btnText.innerHTML = "Read less";
            moreText.style.display = "inline";
        }
}
</script>

我怎么能不使用 Javascript 来满足我的需求呢?我想实现一种更 Angular 的方式,我是 Angular 的新手,请注意我的简洁。提前致谢。

您有几个直接来自 Angular 的选项。核心原则是使用组件中的变量并检查它并更新 in/from 您的模板。

第一个解决方案,模板:

<div uib-accordion-group class="mt-1" ng-repeat="x in data.details" heading="{{data.displayName}}">
    <span id="dots" [hidden]="! showTable"> <table>..</table> </span>
    <span id="more" [hidden]="showTable"> <pre>{{ x|json:4 }}</pre> </span>
    <button (click)="toggleTableVisibility()" id="myBtn">Read more</button>
</div>

而在组件中

showTable = true;

function toggleTableVisibility() {
    this.showTable = ! this.showTable;
}

第二种方案,使用ngIf,只改变模板

<div uib-accordion-group class="mt-1" ng-repeat="x in data.details" heading="{{data.displayName}}">
    <span id="dots" *ngIf="showTable"> <table>..</table> </span>
    <span id="more" *ngIf="! showTable"> <pre>{{ x|json:4 }}</pre> </span>
    <button (click)="toggleTableVisibility()" id="myBtn">Read more</button>
</div>

我没有对此进行测试,因此可能存在拼写错误/解析错误,但这就是它的要点。两者之间的区别在于 [hidden] 的内容被 display: none 隐藏,而 ngIf 的内容只是从 DOM.

中删除

编辑:修改了我的答案以反映对添加切换按钮的问题的更新。