Use svg with angularjs ng-repeat

拥有回忆 提交于 2019-11-30 12:06:34
Ezekiel Victor

The problem is Chrome sees the Angular interpolation str as an invalid value for those attributes (since at least at one time the element actually exists in the DOM -- though invisibly -- with "invalid" values). I have written a solution that is in line with other Angular solutions as to browser handling of special attributes where instead of using x, y, width, and height, you specify ng-x, ng-y, ng-width, and ng-height and the real attributes are set after the values are interpolated.

Here is the solution on JSFiddle. I'm going to submit a patch to Angular to see if we can get this in the core.

HTML

<div ng-app="SampleApp" ng-controller="MainCtrl">
    <svg>
        <g id="g_{{$index}}" ng-repeat="i in range" ng-cloak>
            <rect ng-x="{{i / 5}}" ng-y="{{i / 5}}" ng-width="{{i / 5}}" ng-height="{{i / 5}}"></rect>
        </g>
    </svg>
</div>

JS

angular.module('SampleApp', [], function() {})
    .directive('ngX', function() {
        return function(scope, elem, attrs) {
            attrs.$observe('ngX', function(x) {
                elem.attr('x', x);
            });
        };
    })
    .directive('ngY', function() {
        return function(scope, elem, attrs) {
            attrs.$observe('ngY', function(y) {
                elem.attr('y', y);
            });
        };
    })
    .directive('ngWidth', function() {
        return function(scope, elem, attrs) {
            attrs.$observe('ngWidth', function(width) {
                elem.attr('width', width);
            });
        };
    })
    .directive('ngHeight', function() {
        return function(scope, elem, attrs) {
            attrs.$observe('ngHeight', function(height) {
                elem.attr('height', height);
            });
        };
    });

function MainCtrl($scope) {
    $scope.range = [100, 200, 300];
}

Markus' comment to use late binding is best.

Ie. prefix your attribute with either 'ng-attr-', 'ng:attr:' or 'ng_attr_', like this:

<rect ng:attr:x="{{i / 5}}" ng:attr:y="{{i / 5}}" ng:attr:width="{{i / 5}}" nng:attr:height="{{i / 5}}"></rect>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!