我是 AngularJS 和 SVG 的新手,所以如果我做错了什么,我深表歉意。
我正在尝试使用 AngularJS 创建 SVG 模式:
代码 fiddle : http://jsfiddle.net/WFxF3/
模板:
<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<defs>
<pattern id="grid" width="{{cubeWidth}}" height="{{cubeHeight}}" patternUnits="userSpaceOnUse">
<path d="M 0 0 L 0 {{cubeHeight}}" fill="none" stroke="gray" stroke-width="1" stroke-opacity="0.5"/>
<path d="M 0 0 L {{cubeWidth}} 0" fill="none" stroke="gray" stroke-width="1" stroke-opacity="0.5"/>
<!--<rect width="80" height="80" stroke="red" stroke-width="20" stroke-opacity="0.5" fill="white"/>-->
</pattern>
</defs>
<rect width="100%" height="100%" fill="url(#grid)"/>
</svg>
Controller :
'use strict';
angular.module('gridifyApp')
.controller('MainCtrl', function ($scope) {
var docWidth = document.width;
var columns = 12;
var cubeWidth = docWidth / columns;
var cubeHeight = 44;
$scope.cubeWidth = cubeWidth;
$scope.cubeHeight = cubeHeight;
});
它似乎有效,但我收到控制台错误:
有什么想法吗?
最佳答案
问题是 svg 在 angular 能够执行任何操作之前被解析,因此在 angular 到达它之前,带有双花括号的值是无效的。 Angular 的团队添加了一种方法来定义某种“延迟绑定(bind)”。您可以通过在所需属性前添加 ng-attr-
来使用它。它等到绑定(bind)评估有效并添加具有适当值的真实属性。
在您的情况下,它将是:
<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<defs>
<pattern id="grid" ng-attr-width="{{cubeWidth}}" ng-attr-height="{{cubeHeight}}" patternUnits="userSpaceOnUse">
<path ng-attr-d="M 0 0 L 0 {{cubeHeight}}" fill="none" stroke="gray" stroke-width="1" stroke-opacity="0.5"/>
<path ng-attr-d="M 0 0 L {{cubeWidth}} 0" fill="none" stroke="gray" stroke-width="1" stroke-opacity="0.5"/>
<!--<rect width="80" height="80" stroke="red" stroke-width="20" stroke-opacity="0.5" fill="white"/>-->
</pattern>
</defs>
<rect width="100%" height="100%" fill="url(#grid)"/>
</svg>
应该不会再有错误了。请记住更新您的 Angular 版本。
关于angularjs - 使用 AngularJS 解析 SVG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17890931/