首先,您展示的不是 GeoJSON 对象。 Leaflet 的L.GeoJSON 只接受一组特征,不会使其成为有效的 GeoJSON 对象,因此您不应将其称为 GeoJSON 对象。它是一组 GeoJSON 特征对象。在一个有效的 GeoJSON 特征集合对象中,特征数组的包含如下:
{
"type": "FeatureCollection",
"features": [
// The features
]
}
接下来,您尝试以一种不起作用的方式过滤一些复杂的对象。以下是$filter('filter') 的工作原理:
var simpleArray = [{
'name': 'Foo'
}, {
'name': 'Bar'
}];
$filter('filter')(simpleArray, {'name': 'Foo'}); // Returns array with Foo object
$filter('filter')(simpleArray, {'name': 'Bar'}); // Returns array with Bar object
$filter('filter')(simpleArray, {'name': 'Foobar'}); // Returns empty array
Plunker 示例:http://plnkr.co/edit/I7OGfoJLwaCz0XibcTDB?p=preview
你想用$filter('filter')做什么:
var complexArray = [{
'properties': {
'name': 'Foo'
}
}, {
'properties': {
'name': 'Bar'
}
}];
$filter('filter')(complexArray, {'name': 'Foo'}); // Returns empty array
$filter('filter')(complexArray, {'name': 'Bar'}); // Returns empty array
$filter('filter')(complexArray, {'name': 'Foobar'}); //Returns empty array
Plunker 示例:http://plnkr.co/edit/rUtseKWCeyLiewDxnDDn?p=preview
为什么?因为数组中的对象没有名为name 的属性。它们只有一个名为properties 的属性,它包含一个对象并且确实有一个name 属性。您不能指望过滤器递归地搜索您的对象,直到它找到一个名称属性。它没有。只有当你明确告诉它这样做时它才会这样做:
$filter('filter')(complexArray, {'properties': {'name': 'Foo'}}); // Returns with Foo
$filter('filter')(complexArray, {'properties': {'name': 'Bar'}}); // Returns with Bar
$filter('filter')(complexArray, {'properties': {'name': 'Foobar'}}); // Returns empty
Plunker 示例:http://plnkr.co/edit/LpOvr7Zxw5C5A3Tt5umQ?p=preview
所以你需要设置你的逻辑有点不同,假设你想搜索两个属性,id 和 name 在你的范围内你会拥有:
$scope.search = {
'properties': {}
};
$scope.$watch('search', function (newVal, oldVal) {
if (newVal !== oldVal) {
$scope.data = $filter('filter')($scope.source, $scope.search);
}
}, true);
在你的模板中:
<input ng-model="search.properties.id" placeholder="ID" />
<input ng-model="search.properties.name" placeholder="Name" />
现在,每次您使用其中一个输入时,搜索属性上的监视都会触发,它会过滤源并更新数据。为了在指令中也反映这种变化,您还必须在指令的 link 方法中监视数据对象。在那里,您可以使用新数据更新图层:
scope.$watch('data', function (newVal, oldVal) {
if (newVal !== oldVal) {
geojsonLayer.clearLayers();
geojsonLayer.addData(scope.data);
}
}, true);
Plunker 上一个工作示例中的完整代码:http://plnkr.co/edit/CmfBdmt7BYKPmE22HLvl?p=preview