2016-11-08 75 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