Search code examples
javascriptjqueryangularjsopenlayers

Given the array used with ng-repeat, can I select an individual item created with each item?


I have an angular app that builds a list of zones from map data. The zones are displayed both in a sidebar in divs using ng-repeat, and on the map as vector features. When a user selects a zone on the map, I need to scroll to that zone's DIV in the sidebar. jQuery can perform a scrollTo action given an element, and I know which zone is selected; can I get a reference to the DIV that matches that item?

I cannot use an index because there may be sorting or filtering on the ng-repeat array. Any other options?

EDIT:

Here's some relevant code:

<div class="turf"
    ng-repeat="zone in layers.zones.features"
    ng-class="{
        selected: zone === selectedZone && zone !== highlightedZone,
        hover: zone === highlightedZone
    }"
    ng-click="selectZone(zone); $event.stopPropagation()">

    <h2>{{zone.name}}</h2>
    <input type="text" class="form-control" ng-model="zone.name" />
    {{zone.users}} users present
</div>

Openlayers will call a function when one of those zones on the map is clicked:

zoneLayer.events.register("featureselected", null, function(e){
    var zone=e.feature;
    var element = null; // how do I get the element?

    $(element).scrollTo(); // or similar
});

Solution

  • If your zone objects have ID or some other identifier then add ID to your div

    <div class="turf"
        id="{{zone.ID}}"
        ng-repeat="zone in layers.zones.features"
        ng-class="{
            selected: zone === selectedZone && zone !== highlightedZone,
            hover: zone === highlightedZone
        }"
        ng-click="selectZone(zone); $event.stopPropagation()">
    
        <h2>{{zone.name}}</h2>
        <input type="text" class="form-control" ng-model="zone.name" />
        {{zone.users}} users present
    </div>
    

    Then find your zone by id

    zoneLayer.events.register("featureselected", null, function(e){
        var zone=e.feature;
        var element = $("#" + zone.ID); // how do I get the element?
    
        $(element).scrollTo(); // or similar
    });
    

    If you can't afford to add IDs to divs then add data-zoneID attribute and find element by that attribute var element = $("div[data-zoneID=" + zone.ID + "]");