【问题标题】:Clear previous data before request在请求之前清除以前的数据
【发布时间】:2016-11-08 12:12:35
【问题描述】:

我有一个 HTML 模板,它从控制器的数组中加载数据并将它们保存在一个表中。我也有一个指令,它对表行进行嵌入。数据数组正在根据 API 请求进行填充。在新请求之后,我将请求结果合并到我的表中。正在为每个请求添加一组行,而不是清除以前的结果。

我已经调试了我的控制器代码以检查我的数组的状态,并且在每次请求之前它都会被清除。这是肯定的。但是,新结果会添加到以前的结果中。我认为原因可能在我的嵌入指令模板中。

模板如下:

<div class="row">
    <div class="col-md-12">
        <div id="results" ng-show="results.length > 0">
            <table class="table result-table">
                <thead>
                    <tr>
                        <th>1</th>
                        <th>2</th>
                        <th>3</th>
                        <th>4</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="result in results" my-result></tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

这是我的嵌入指令的代码:

angular.module('app').directive('myResult',
['$compile',
function ($compile) {
    return {
        transclude: true,
        templateUrl: '/Scripts/app/templates/resultTemplate.html',
        compile: function (tElement, tAttr, transclude) {
            var contents = tElement.contents().remove();
            var compiledContents;
            return function (scope, iElement, iAttr) {
                if (!compiledContents) {
                    compiledContents = $compile(contents, transclude);
                }
                compiledContents(scope, function (clone, scope) {
                    iElement.replaceWith(clone);
                });
            };
        }
    }
}]);

最后是用于嵌入的模板:

<tr class="big-bord">
    <td colspan="4"><h3>{{result.fullName}}</h3></td>
</tr>
<tr ng-repeat="item in result.items">
    <td>{{item.value1}}</td>
    <td>{{item.value2}}</td>
    <td>{{item.value3}}</td>
    <td>{{item.value4}}</td>
</tr>

如何在每次 API 请求之前清除我的结果?

【问题讨论】:

  • 您使用的是哪个版本的 Angular?根据 Angular 1.4 文档,compile(transclude) 已被弃用。
  • jbrown,我使用 Angular 1.5.7。什么来代替嵌入?
  • 角度文档状态“使用传递给链接函数的 transclude 函数”。在这里阅读更多:docs.angularjs.org/api/ng/service/$compile
  • 谢谢,但我仍然不确定它是否能解决我的问题

标签: javascript angularjs ajax duplicates asp.net-ajax


【解决方案1】:

我解决了我的问题。事实证明,一个表中允许有多个

标签。所以我只是将我的 ng-repeat 移动到 标签:
<tbody ng-repeat="result in results">
    <tr class="big-bord">
        <td colspan="4"><h3>{{result.fullName}}</h3></td>
    </tr>
    <tr ng-repeat="item in result.items">
        <td>{{item.value1}}</td>
        <td>{{item.value2}}</td>
        <td>{{item.value3}}</td>
        <td>{{item.value4}}</td>
    </tr>
</tbody>

所以,我根本不需要任何指令。

【讨论】:

  • 如果要避免多个tbody,可以在第一行使用ng-repeat-start,在第二行使用ng-repeat-endMore information.
猜你喜欢
  • 2021-02-15
  • 2016-06-04
  • 2018-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多