2015-09-17 27 views
0

我一直在尝试将字符串值传递给指令,但它似乎只接受整数或浮点数。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> 

正如你可以看到第二个矩形在“填充”中没有任何价值。

如何传递包含颜色代码的字符串值?

+0

在指令作用域对象中使用了错误的操作符。尝试使用'@'而不是'='。如果你是属性中的硬编码值,则不存在2路绑定 – charlietfl

+0

是的,应该使用@作为单路绑定。 =用于双向绑定。 –

+0

无论哪种情况,传递给指令的值都应该是可评估的表达式。 '333'因为它计算为一个整数而起作用。但是'FFc000'不会评估为字符串,它会尝试将其评估为变量名称,该变量名称不存在于名称空间中,因此结果为“未定义”。如果要绑定到字符串文字,请将带引号的字符串文字放入属性中,如下面的回答下面的答案所示。 –

回答

1

我尝试两种解决方案:

由1- tcolor和vcolor 2 - 变“=”被“@”用引号括起来

都工作的价值,而是根据@ ste2425的解决方案Seconde系列是不好的做法,所以选择了第一个。

感谢@charlietfl和@Diana R

3

通常字符串必须用单引号:

<ooda-bar width="500" total="100" value="60" tcolor="333" vcolor="'ffc000'"></ooda-bar> 

更新从@ ste2425基础上添加注释解释:

“硬编码字符串应包含在第二对引号,加倍与否,因为角度会认为你指的是一个范围变量,否则试图对它进行绑定,但也应该提到,在你的视图中加入硬编码值是非常糟糕的做法“

+1

为什么这会降低投票率?这是正确的解决方案,即使它没有解释为什么。 –

+1

这应该不是已经被低估了,它回答了这个问题。硬编码的字符串应该用第二对引号括起来,因为angular会认为你引用了scope变量,然后尝试对它执行绑定。但是,它也应该提到,在你的观点中使用硬编码值是非常糟糕的做法。如果您在视图中硬编码值,小猫和小象将会死亡。 – ste2425

+0

@ ste2425感谢您的解释 –

相关问题