我正在通过开发 map 指令来学习 angularjs。最外层的指令是 myMap,然后 myCircle、myMarker 等...是子指令。此时,我只有 myMap 和 myCirle 指令。 如果我不使用 ng-repeat, map 和圆圈工作正常。一旦我使用 ng-repeat,AngularJS 就会抛出异常
类型错误:无法读取 https://code.angularjs.org/1.2.21/angular.js:3012:13 处 null 的属性“insertBefore” ... 当我开始绘制 map 时。我花了很多时间但仍然不知道如何解决它。任何帮助将不胜感激。
这是我的笨蛋:http://plnkr.co/edit/LI7lh28OAhh59HeuL7O1?p=preview
app.directive('myMap', function () {
return {
restrict: 'E',
replace: true,
transclude: true,
template: "<div ng-transclude id='mapCanvas' ></div>",
scope: {
center: '=',
zoom: '='
},
controller: function ($scope) {
console.log('map directive: controller...')
this.drawCircle = function (data) {
var circle = new google.maps.Circle({
map: $scope.map,
center: new google.maps.LatLng(data.center.latitude, data.center.longitude),
radius: data.radius,
strokeColor: data.strokeColor,
strokeOpacity: data.strokeOpacity,
strokeWeight: data.strokeWeight,
fillColor: data.fillColor,
fillOpacity: data.fillOpacity
});
return circle;
};
},
link: function (scope, element, attrs) {
var mapOptions = {
center: new google.maps.LatLng(scope.center.latitude, scope.center.longitude),
zoom: scope.zoom
};
// comment this line out will make the directives work without problem.
scope.map = new google.maps.Map(document.getElementById("mapCanvas"), mapOptions);
console.log("Map directive:Link: initialize the map ..." + JSON.stringify(scope.center));
}
}
});
app.directive('myCircle', function ($timeout) {
return {
restrict: 'E',
replace: true,
scope: {},
require:'^myMap',
link: function (scope, element, attrs, ctrl) {
console.log("circle directive:Link..." );
var data = {
center:{latitude: attrs.lat, longitude:attrs.lng},
radius: parseFloat(attrs.radius),
strokeColor: attrs.strokeColor,
strokeOpacity: attrs.strokeOpacity,
strokeWeight: attrs.strokeWeight,
fillColor: attrs.fillColor,
fillOpacity: attrs.fillOpacity
};
$timeout( function(){
console.debug('callling the map.drawCircle...')
ctrl.drawCircle(data)
}, 1000);
}
}
});
最佳答案
这是因为在使用以下语句创建 map 时:
scope.map = new google.maps.Map(document.getElementById("mapCanvas"), mapOptions);
mapCanvas
元素中的内容将被删除并替换为 Google map 小部件。
然后,当 ng-repeat
尝试从 map.circles
填充元素时,它找不到应附加这些填充元素的原始元素。
要解决此问题,您可以将 myMap
指令的模板更改为类似以下内容,以防止原始元素被替换。
template: "<div><div id='mapCanvas'></div><div ng-transclude></div></div>",
Plunker 示例: http://plnkr.co/edit/A0yYyoB5LCfTM0ixVcMy?p=preview
PS。my-circle
指令的属性绑定(bind)中有很多拼写错误。
关于angularjs - 嵌套指令和 ng-repeat 异常 TypeError : Cannot read property 'insertBefore' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25320571/