我一直在嘗試將字符串值傳遞給指令,但它似乎只接受整數或浮點數。AngularsJS如何將字符串傳遞給指令?
這是代碼:
app.directive('oodaBar', function(){
return {
restrict: 'EA',
scope: {
total: '=total',
value: '=value',
width: '=width',
tcolor: '=tcolor',
vcolor: '=vcolor'
},
templateUrl: 'partials/ooda-bar.html'
};
OODA-一個bar.html:
<svg width="{{width + 25}}" height="50">
<rect x="25" width="{{width}}" height="19" fill="#{{tcolor}}"></rect>
<rect x="25" width="{{width * (value/total)}}" height="19" fill="#{{vcolor}}"></rect>
<line x1="{{width + 25}}" y1="19" x2="{{width + 25}}" y2="38" stroke="#333" />
<line x1="{{width * (value/total) + 25}}" y1="19" x2="{{width * (value/total) + 25}}" y2="38" stroke="#333" />
<text x="{{width * (value/total) - 5 + 25}}" y="40" fill="#333" style="direction:rtl">{{value}}</text>
<text x="{{width - 5 + 25}}" y="40" fill="#333" style="direction:rtl">{{total}}</text>
</svg>
我加入這顯示它:
<ooda-bar width="500" total="100" value="60" tcolor="333" vcolor="ffc000"></ooda-bar>
的問題是,我得到了這在瀏覽器中:
<svg width="525" height="50">
<rect x="25" width="500" height="19" fill="#333"></rect>
<rect x="25" width="300" height="19" fill=""></rect>
<line x1="525" y1="19" x2="525" y2="38" stroke="#333"></line>
<line x1="325" y1="19" x2="325" y2="38" stroke="#333"></line>
<text x="320" y="40" fill="#333" style="direction:rtl">60</text>
<text x="520" y="40" fill="#333" style="direction:rtl">100</text>
</svg>
正如你可以看到第二個矩形在「填充」中沒有任何價值。
如何傳遞包含顏色代碼的字符串值?
在指令作用域對象中使用了錯誤的操作符。嘗試使用'@'而不是'='。如果你是屬性中的硬編碼值,則不存在2路綁定 – charlietfl
是的,應該使用@作爲單路綁定。 =用於雙向綁定。 –
無論哪種情況,傳遞給指令的值都應該是可評估的表達式。 '333'因爲它計算爲一個整數而起作用。但是'FFc000'不會評估爲字符串,它會嘗試將其評估爲變量名稱,該變量名稱不存在於名稱空間中,因此結果爲「未定義」。如果要綁定到字符串文字,請將帶引號的字符串文字放入屬性中,如下面的回答下面的答案所示。 –