2015-04-06 25 views
2

這是我做了什麼如何顯示過濾器函數中的數據/數組以查看內部表達式?

<div ng-app="myApp" ng-controller="PeopleCtrl">  
<table border="1" ng-init="ageToShow=(people| underTwenty: 20).length >= 1"> 

而且我underTwenty功能是爲下

myApp.filter('underTwenty', function() { 

    return function(values, limit) { 
    var returnValue = []; 
    angular.forEach(values, function(val, ind) { 
     if (val.age < limit) 

     returnValue.push(val); 
     }); 
    return returnValue; 
    }; 

我想顯示在我看來,的returnValue數組作爲表達這樣

<div ng-app="myApp" ng-controller="PeopleCtrl">  
    <table border="1" ng-init="ageToShow=(people| underTwenty: 20).length >= 1"> 
{{ageToShow}} 

我知道這不是正確的方式,但它是什麼..請幫助...

Plunkerhttp://plnkr.co/edit/ceeF5tXFlBqInW5J3bdq?p=preview

+0

你能解釋一下你想達到什麼嗎,用簡單的英語?鑑於人員名單,該頁面應該顯示什麼? – 2015-04-06 08:39:08

+0

「我想在我的視圖中顯示returnValue數組,如下所示:」 在這種情況下,您不需要檢查ageToShow中的長度。你的問題不清楚。看到這個plunkr:http://plnkr.co/edit/LNhiN71UQu2bdCUIw8SR?p = preview – 2015-04-06 09:13:45

回答

1

在這裏找到更新的代碼:

<body> 
<div ng-app="myApp" ng-controller="PeopleCtrl"> 


<table border="1" ng-init="ageToShow=(people| underTwenty: 20).length >= 1"> 

    {{people| underTwenty: 20}} 
<tr> 
<th>Id</th> 
<th>Name</th> 
<th ng-if="!ageToShow">Age</th> 
</tr> 
<tr ng-repeat="person in people| underTwenty: 20" > 
<td><span>{{person.id}}</span> 
</td> 
<td><span>{{person.name}}</span> 
</td> 
<td ng-if="!ageToShow"><span>{{person.age}}</span> 
</td> 
</tr> 
</table> 

</div> 
</body> 
</html> 

希望這是你想要的

+0

當我嘗試給{{people}}在html頁面中有表達式時, ............. [{「id」:1,「name」:「Peter」,「age」:25},{「id」:2,「name」:「David」 , 「年齡」:19},{ 「ID」:3 「名稱 」:「 阿尼爾」, 「年齡」:30},{ 「ID」:4 「名稱」: 「Chean」, 「年齡」: 20},{「id」:5,「name」:「Niladri」,「age」:18}]但我需要的是過濾數組....... only {「id」:2,「名稱「:」大衛「,」年齡「:19},..... {」id「:5,」name「:」Niladri「,」age「:18} – 2015-04-06 13:12:34

+0

您可以使用這個{ {人| underTwenty:20}} – Reena 2015-04-07 04:23:24

+0

謝謝你@ Reena它現在可以工作......這是我正在搜索的那個 – 2015-04-07 07:12:21

1

在控制器添加新的過濾器功能:

$scope.criteriaMatch = function(criteria) { 
    return function(person) { 
    return person.age < criteria; 
    }; 

並鑑於變化:

<tr ng-repeat="person in people| filter:criteriaMatch(20)" > 

而表顯示ONY 2行與年齡小於20

http://plnkr.co/edit/PonnLcvrjEEHhceSqD0g?p=preview

+0

但我沒有問到我需要的表格數據,我需要的是一個原始數據,它將被稱爲{「id」:2,「name」:「David」,「age」:19},.... 。{「id」:5,「name」:「Niladri」,「age」:18} ...... – 2015-04-06 13:18:13

1

在您的ng-repeat中,使用多個過濾器來過濾基於年齡的人。

<tr ng-repeat="person in people| filter: search | underTwenty: 20" > 

我喜歡你的控制器保持過濾器,而不是分開的,因爲,如果需要的話可以重複使用在其他視圖該過濾器爲好辦法。否則,您可能需要將代碼粘貼到多個控制器中。

但保持登錄在視圖中是一個壞主意。相反在你的控制器中,你可以創建該變量並進行檢查。這將從邏輯中移除演示文稿。

它將成爲:

$scope.ageToShow = $filter('underTwenty')($scope.people, 20).length >= 1; 

注入$零一二三九三九零七六六零零七八零四二一零三二一零到控制器中。

DEMO

1

更改這一行代碼:<tr ng-repeat="person in people| filter: search" ><tr ng-repeat="person in people| underTwenty: 20" >。由於這個原因,(我的理解這是你想要什麼就。)該表將只包含這些項目,其中年齡小於20

相關問題