2

I am new both to AngularJS and SVG so if i am doing something terribly wrong i apologize.

I am trying to create an SVG pattern with AngularJS:

Code fiddle: http://jsfiddle.net/WFxF3/

Template:

<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;
  });

It seems to work and yet I get a console error: console error for angularJS view

Any ideas why?

Guy
  • 12,488
  • 16
  • 79
  • 119
  • It might be too late to help you specifically but I have just published an article on AngularJS + SVG. http://www.codeproject.com/Articles/709340/Implementing-a-Flowchart-with-SVG-and-AngularJS – Ashley Davis Jan 19 '14 at 06:55

2 Answers2

18

The problem is svg is being parsed before angular is able to do anything so the value with double curly braces is invalid before angular gets to it. Angular's team has added a way to define some kind of "delayed binding". You can use it by prefixing desired attribute with ng-attr-. It waits untill the binding evaluation is valid and adds real attribute with proper value. In your case it would be:

<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>

There should be no errors anymore. Remember to update your angular version.

Patryk Ziemkowski
  • 1,490
  • 12
  • 26
2

SVG parsing happens before AngularJS can set any variable. You might try to create the SVG programmatically:

Community
  • 1
  • 1
David Riccitelli
  • 7,491
  • 5
  • 42
  • 56