羅伯特是對的。
這是我的解決方案。 祕訣就是使用createElementNS。因此,瀏覽器明白它是一個svg元素而不是html元素。
這裏是指令
app.directive('multilinesvgtext', function() {
var xmlns = "http://www.w3.org/2000/svg";
var myLink = function (scope, elem, attrs) {
attrs.$observe('contenu', function (val) {
var data = val;
var generateTSpan = function (lineOftext) {
var tspanElement = document.createElementNS(xmlns, 'tspan');
tspanElement.setAttribute('x', attrs.x);
tspanElement.setAttribute('dy', attrs.dy);
tspanElement.setAttribute('class', attrs.class);
tspanElement.setAttribute('xml:space', 'preserve');
var tspanContent = document.createTextNode(lineOftext);
tspanElement.appendChild(tspanContent);
return tspanElement;
};
// We delete the old children
while (elem[0].firstChild) {
elem[0].removeChild(elem[0].firstChild);
}
var lines = data.split('\n');
for(var i= 0; i < lines.length; i++)
{
var textContent = lines[i]!=='' ? lines[i] : ' ';
var newTspanElement = generateTSpan(textContent);
elem[0].appendChild(newTspanElement);
}
});
};
return {
restrict: 'A',
link: myLink
};
}
);
這可以是這樣的用途:
<text multilinesvgtext x="30" y="168" fill="#FFFFFF" data-dy="13" class="myclass" data-contenu="{{mydata}}"></text>
我的指令添加TSPAN孩子在MYDATA文本的每一行,並使用數據DY屬性爲DY屬性爲這個tspan。
由於tspan在html命名空間中創建爲未知的tspan元素,而不是SVG命名空間中的真正tspan元素。您需要使用DOMParser,並確保tspan具有SVG xmlns屬性。 –
謝謝。我明白。我將嘗試創建一個指令並使用createElementNS –