2016-08-30 57 views

回答

1

省略回调并把初始化函数在一个指令

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY" 
     async defer> 
</script> 

<init-map map="vm.map"> 
</init-map> 

JS

app.directive("initMap", function($window) { 
    return { 
     restrict: "E", 
     template: '<div style="height: 400px;">XXX</div>', 
     link: function(scope,elem,attrs) { 
      var jElem = elem.find('div')[0]; 
      scope[attrs.map] = new google.maps.Map(jElem, { 
       center: {lat: -34.397, lng: 150.644}, 
       zoom: 8 
      }); 
     } 
    }; 
}); 

上述指令将创建使用由map属性所定义的范围的变量的新映射。

The DEMO on JSFiddle