带有过滤器的Angular ng-repeat不使用http.get更新

时间:2016-09-19 20:27:41

标签: angularjs ng-repeat ng-filter

我正在使用查询过滤数组(结果)。通过删除过滤器,结果可准确显示所有元素。通过删除更新结果并初始化结果以包含元素的http.get,过滤器可以准确过滤。

使用过滤器和http.get更新结果时,即使结果包含数据,也会显示无结果的消息。我已经确认http.get正确更新了结果(正如下面正确显示的 {{results}} 所示)。以下是 {{results}} 显示的内容:

[
  {
    "name": "Company Number 1 ",
    "description": "description of 1 "
  },
  {
    "name": "Company Number 1 ",
    "description": "description of 1 "
  },
  {
    "name": "Company Number 2 ",
    "description": "description of 2 "
  }
]

的index.html

<div class="form-group label-floating">
    <label class="control-label" for="addon1">Filter</label>
    <input id="addon1" class="form-control" type="text" data-ng-model="query">
</div>

{{results}} <!--This works properly-->

<table class="table table-striped" id="resultsTable">
    <tbody>
    <tr data-ng-show="resultsFilter.length === 0">
        <td class="center" colspan="3">No results found.</td> <!--This message appears even when results should have elements-->
    </tr>
    <tr data-ng-repeat="result in resultsFilter = (results | filter:query | limitTo:displayNum) track by result.name">
        <td>
            <button class="btn btn-primary btn-block">
                {{result.name}}
            </button>
        </td>
    </tr>
    </tbody>
</table>

angular.js

$scope.query = "";
$scope.displayNum = 20;
$scope.results = [];
...
$scope.updateResults = function () {
    $http({
    method: "GET",
    url: requestUrl,
    params: {id: $scope.identifierInHierarchy.companyId}
})
    .then(function successCallback(response) {
        $scope.query = "";
        $scope.results = [];
        response.data.forEach(function (entry) {
            $scope.results.push({
                name: "Company Number " + entry.CompanyNumber,
                description: "description of " + entry.CompanyNumber
            });
        });
    },
        function errorCallback(response) {
        });
}

更新:否,将resultsFilter更改为结果无法解决问题。我也认为这是不正确的,因为保持resultsFilter和静态初始化结果将正确过滤(如前所述)。

2 个答案:

答案 0 :(得分:0)

你正在使用resultsFilter到处声明的地方。它应该是results

<table class="table table-striped" id="resultsTable">
<tbody>
<tr data-ng-show="{{results.length}} === 0">
    <td class="center" colspan="3">No results found.</td> <!--This message appears even when results should have elements-->
</tr>
<tr data-ng-repeat="result in results = (results | filter:query | limitTo:displayNum) track by result.name">
    <td>
        <button class="btn btn-primary btn-block">
            {{result.name}}
        </button>
    </td>
</tr>
</tbody>

答案 1 :(得分:0)

因为这个

而没有显示任何结果
<tr data-ng-show="resultsFilter.length === 0">
        <td class="center" colspan="3">No results found.</td> <!--This message appears even when results should have elements-->
    </tr>

resultsFilter 范围仅限于ng-repeat,您尝试在范围之上访问它。所以请仅使用结果进行更改,然后进行测试。

希望这会有所帮助!!