2016-11-08 60 views
0

我想在我的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}}]; 
    }]); 

HTLM代码:

<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

回答

0

原因你看到的是,一旦你'清除'id过滤器,值仍然是一个空字符串,所以过滤器仍然尝试匹配test.id属性,因此只查看具有该属性的记录。为了真正清除它,您需要设置未设置的.test属性。您可以通过添加一个手表为id过滤器,并取消设置它是一个空字符串:

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

非常感谢。它效果不错 –

+0

不客气。请将答案标记为已接受。 – GPicazo