Angular过滤器嵌套属性清除



我正在尝试在JSON对象的子元素上应用过滤器。

它工作得很好,但是当我清除我的过滤器时,没有我的子元素的属性不显示。

你能帮我做这件事吗?

我不能修改JSON结构JS代码:

'use strict';
angular.module('filterExample', [])
    .controller('filterController', ['$scope', function($scope) {
    $scope.amis =
        [{nom:'John', tel:'01-23-45-67-89', age:10, test:{id:3}},
         {nom:'Mary', tel:'02-34-56-78-91', age:19},
         {nom:'Mike', tel:'03-45-67-89-12', age:21, test:{id:5}},
         {nom:'Adam', tel:'04-56-78-91-23', age:35},
         {nom:'Julie', tel:'05-67-89-12-34', age:29, test:{id:7}}];
    }]);

html代码:

  <head>
    <meta charset="UTF-8" />
    <title>Exemple 2 du filtre filter</title>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
    <script src="script.js"></script>
  </head>
  <body ng-app="filterExample">
    <div ng-controller="filterController">
      <h4>Objet pour le prédicat</h4>
      <p>
        N'importe quel champ <i>(search.$)</i> : <input ng-model="search.$"> <br/>
        Seulement à partir du nom <i>(search.nom)</i> : <input ng-model="search.nom"><br/>
        Seulement à partir de l'âge <i>(search.age)</i> : <input ng-model="search.age"> <br/>
        Seulement à partir du téléphone <i>(search.tel)</i> : <input ng-model="search.tel"><br/>
        Seulement à partir test <i>(search.test.id)</i> : <input ng-model="search.test.id"><br/>
      </p>
      <table>
        <tbody>
          <tr>
            <th>Nom</th>
            <th>Âge</th>
            <th>Téléphone</th>
          </tr>
          <tr ng-repeat="ami in amis | filter:search">
            <td>{{ami.nom}}</td>
            <td>{{ami.age}}</td>
            <td>{{ami.tel}}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </body>
</html>

下面是一个例子:https://plnkr.co/edit/7RlfmKU2UkM13z0ogwmh?p=preview

您看到的原因是,一旦您'清除' id过滤器,id的值仍然是一个空字符串,因此过滤器仍然试图匹配test.id属性,因此只查看具有该属性的记录。为了真正清除它,您需要设置unset .test属性。您可以通过为id过滤器添加监视并在它是空字符串时取消设置来实现:

$scope.$watch('search.test.id', function(newVal, oldVal) {
    if (newVal !== undefined && newVal.length === 0) {
        $scope.search.test = undefined;
    }
});

最新更新