AngularsJS如何将字符串传递给指令?

时间:2015-09-17 13:17:42

标签: angularjs

我一直在尝试将字符串值传递给指令,但它似乎只接受整数或浮点数。

这是代码:

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>

正如你所看到的那样,第二个矩阵在&#34;填充&#34;。

中没有任何价值

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

2 个答案:

答案 0 :(得分:3)

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

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

更新以根据@ ste2425的评论添加说明:

“硬编码字符串应该用第二对引号括起来,不管是否加倍,因为angular会认为你引用了一个范围变量,并尝试对它进行绑定。但是也应该提到它是非常糟糕的练习将硬编码值放在视图中“

答案 1 :(得分:2)

我尝试了两种解决方案:

1-在tcolor和vcolor中用“@”改变“=” 2-将值括在引号

两者都有效,但根据@ ste2425,seconde解决方案是不好的做法,因此选择了第一个。

感谢@charlietfl和@Diana R