我一直在尝试将字符串值传递给指令,但它似乎只接受整数或浮点数。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'不会评估为字符串,它会尝试将其评估为变量名称,该变量名称不存在于名称空间中,因此结果为“未定义”。如果要绑定到字符串文字,请将带引号的字符串文字放入属性中,如下面的回答下面的答案所示。 –