我是 angularJs 的新手。当"localid"被更改时,我正在尝试在链接内重新运行 init() 函数,但它说
var elm = angular.element(element[0].getSVGDocument().getElementsByTagName("path"));
即使它在页面加载时第一次工作,也为空。
类型错误: 无法读取 null 的属性"getElementsByTagName"
我在谷歌上搜索了 5 个多小时,但我找不到原因。我错过了什么?
(function() {
'use strict';
angular
.module('neuroSeoulFinance')
.directive('seoulmap', seoulMap);
/** @ngInject */
function seoulMap($log) {
var directive = {
restrict: 'E',
template: '<object id="seoulmap" class="localMap" data="../assets/images/seoul.svg" type="image/svg+xml" width="80%"></object>',
replace: true,
scope: {
localid : "="
},
link: function(scope, element, attrs) {
var init = function() {
var elm = angular.element(element[0].getSVGDocument().getElementsByTagName("path"));
$log.log(elm);
for(var i=0; i<elm.length; i++) {
if(elm[i].id == scope.localid.id) {
elm[i].style.fill = attrs.highlight;
}
else {
elm[i].style.fill = "#e1e3e4";
}
}
};
scope.$watch('localid', function(newValue, oldValue) {
if (newValue){
init(); // <-- it doesn't work.
// var ealm = angular.element(element[0].getSVGDocument().getElementsByTagName("path"));
// ^ it also return null..
$log.log("I see a data change!");
}
}, true);
if(element[0].getSVGDocument()) {
$log.log("init");
init();
} else {
$log.log("load");
element.on("load",init);
}
}
};
return directive;
}})();
请参阅如何检查嵌入的 SVG 文档是否已加载到 html 页面中?
如果getSVGDocument返回null,则表示该元素尚未加载,因此如链接中所述,请使用超时,并且由于您使用角度,请使用$timeout。
我在 element.on("load") 完成后更改了$watch代码。感谢您的有用评论。
if(element[0].getSVGDocument()) {
init();
} else {
element.on("load",function(){
scope.$watch('localid', function(newValue, oldValue) {
if (newValue){
init();
}
});
});
}