首页 > 解决方案 > Using something like ngRepeat in Javascript

问题描述

I want to populate a drop-down list with data from an array. The code below is something I would do if I was working with angularJS. I want to know if there is a way to do this in javascript or somehow allow ng-options to work here.

  var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
  var mapOptions = {
    zoom: 4,
    center: myLatlng
  };

  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    var city = ["NewYork", "Chicago", "Florida"];

  var contentString = 
      `<div class="dropdown">
   <select>
     <option ng-options="item for item in ${city}">{{item}}</option>
   </select>
</div>`;

  var infowindow = new google.maps.InfoWindow({
      content: contentString
  });

  var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: 'Uluru (Ayers Rock)',
//    zIndex: Math.round(myLatlng.lat() * -100000) << 5
  });
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(contentString);
    infowindow.open(map,marker);
  });

DEMO: https://jsfiddle.net/spdmu6we/5/

标签: javascripthtmlarraysangularjsangularjs-directive

解决方案


根据您的评论,您更喜欢在没有 HTML `' 的情况下执行此操作。

因此,您有两个选择: 1. 使用字符串解析来构建 HTML 字符串,然后将其作为内容传递 2. 将您拥有的字符串解析到 DOM 节点并使用我提供的代码。

这用通用代码替换了 GMap 的东西。您仍然可以使用与 DOM 相关的代码。

这是一个解决方案:

var city = ["NewYork", "Chicago", "Florida"];
const pre = '<div class="dropdown"><select>';
const post = '</select></div>';
let options = '';
city.forEach(city => {
  let o = `<option value=${city}>${city}</option>`;
  options += o;
});
content = pre + options + post;

var infowindow = document.createElement('div');
infowindow.innerHTML = content;
infowindow.style.display = 'none'

var marker = document.createElement('button');
marker.innerText = "Click me";

marker.addEventListener('click', () => {
  document.body.appendChild(infowindow);
  infowindow.style.display='block';
});
document.body.appendChild(marker);
<div id="map-canvas"></div>


推荐阅读