[英]Angularjs filter allow null value using custom comparator not working?
大家好。 我使用AngularJs在表格中使用ng-repeat指令顯示數據,並使用文本框來過濾貓的“顏色”屬性。 請注意,某些cat具有null Color屬性。
一旦我在文本框中鍵入一些文本並清除它,所有color屬性為null的cat都消失了。
我設置了一個自定義比較器,在expected === ''
返回true,但它不起作用。 實際上,一旦搜索文本框被放入一些文本並且之后被清除,所有具有顏色property === null
cat將永遠不會顯示,即使我讓比較器始終返回true。
在ng-repeat中使用過濾器時,有沒有辦法允許空值? 先感謝您!!
JS小提琴演示: http : //jsfiddle.net/gLL7wvcL/2/
我的數據(貓的數組)
$scope.cats = [
{'Name': 'John',
'Sex': 'Male',
'Color': 'Black'},
{'Name': 'Rose',
'Sex': 'Female',
'Color': 'White'},
{'Name': 'Cindy',
'Sex': 'Female',
'Color': 'Yellow'},
{'Name': 'David',
'Sex': 'Male',
'Color': 'Black'},
{'Name': 'Garen',
'Sex': 'Male',
'Color': null},
{'Name': 'Jim',
'Sex': 'Male',
'Color': null},
{'Name': 'Charotte',
'Sex': 'Female',
'Color': 'Black'}
];
並且兩個比較器都不起作用,一旦搜索文本框被放入一些文本並在之后被清除,所有具有color屬性=== null的cat將永遠不會顯示。
$scope.myComparator = function (actual, expected)
{
if (expected === '')
return true;
else
{
var text = ('' + actual).toLowerCase();
return text.indexOf(expected) > -1;
}
};
$scope.myComparator = function (actual, expected)
{
return true;
};
這里的問題是,在清除輸入后,過濾器模型如下所示:
{"Color": ""}
所以空字符串將不匹配顏色為null
顏色。 你需要做的就是刪除“Color”屬性,如果它是null
,可能是在更改時。 在這種情況下,您根本不需要myComparator
:
$scope.clear = function() {
if ($scope.search.Color === null) {
delete $scope.search.Color;
}
};
你會用到的
ng-repeat="cat in cats | filter:search"
另一種方法是使用過濾器函數,與整個對象而不是屬性進行比較,並將標准附加到控制器范圍。
標記:
<tr ng-repeat="cat in cats | filter:myComparator">
控制器:
$scope.myComparator = function (actual)
{
var expected = $scope.filter;
if (expected === '')
{
return true;
}
else
{
var text = ('' + actual.Color).toLowerCase();
return text.indexOf(expected) > -1;
}
};
更新小提琴中的完整示例: http : //jsfiddle.net/gLL7wvcL/3/
if(expected ==='')將檢查空字符串,而不是null。
嘗試替換它
如果(!期待).....
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.