You could do something like what I did in the plunker that is forged from yours . Create a factory where you save marker objects, return them to the controller as called, and then filter them according to filterTerm
(which is not included in the scope of your controller in your original plunter, by the way).
app.factory('myMarkers', function() { var markers = { m1: { lat: 51.505, lng: -0.09, data: 'a' }, m2: { lat: 51, lng: 0, data: 'ab' }, m3: { lat: 51, lng: 0.1, data: 'abc' }, m4: { lat: 51, lng: 0.14, data: 'abcd' } }; function filterMarkersBy(term) { return _.filter(markers, function(marker) { return marker.data.indexOf(term) > -1; }); } return { markers: markers, filterMarkersBy: filterMarkersBy } });
And then in your controller, you can initialize the map by placing all the markers on $scope
(using angular.extend($scope, { markers: myMarkers.markers });
), and then look at the value of your $scope.filterTerm
to filter the $scope.markers
object $scope.markers
respectively.
... angular.extend($scope, { markers: myMarkers.markers }); $scope.filterTerm; $scope.$watch(function() { return $scope.filterTerm; }, function(newVal) { if (newVal) { console.log(newVal); $scope.markers = myMarkers.filterMarkersBy(newVal); } });
Now it is filtered on the fly and adds backward markers when you reduce the filter term. Note that I use the lodash _.filter()
method to filter in the factory, but you probably already got lodash as a dependency.
source share