【问题标题】:add svg element at runtime in angular with 2 way data binding在运行时以 2 路数据绑定的角度添加 svg 元素
【发布时间】:2015-08-12 16:38:09
【问题描述】:

我想在运行时使用 ng-attr-x1={{some scope varaible}} 添加 svg 元素行。 我尝试了两种方法: 我尝试使用 $compile 的一种方式:

var g=angular.element(document.createElementNS("http://www.w3.org/2000/svg", "g"));
var line=$compile('<line ng-attr-x1={{$scope.array[array.length-1].x1}} ng-attr-y1={{$scope.array[array.length-1].y1}} ng-attr-x1={{$scope.array[array.length-1].x2}} ng-attr-x1={{$scope.array[array.length-1].y2}} style="with mandatory styling for line">')($scope);
g.append(line);
parentg.append(g);

在此方法中,行不显示,g 以 0px 的高度和宽度显示。

我有两种方式:

var line=angular.element(document.createElementNS("http://www.w3.org/2000/svg", "line"));
line.attr('ng-attr-x1','scopeVariable');
line.attr('ng-attr-x2','scopeVariable');
line.attr('ng-attr-y1','scopeVariable');
line.attr('ng-attr-Y2','scopeVariable');

在这个 ng-attr 属性中没有解析为 x 和 y。在 DOM 中显示为

【问题讨论】:

    标签: angularjs svg


    【解决方案1】:

    这可能来得太晚了,无法帮助你,但我在同一个问题上卡了一会儿。

    原来 $compile 可以获取使用 document.createElementNS() 创建的元素 - 像这样:

    var actApp = angular.module('actApp', []);
    
    actApp.controller('shapeController', ['$scope', '$compile',
      function shapeController($scope, $compile) {
        $scope.color = 'green';
    
        var svgEle = $(document.getElementById('mySvgElement'));
    
        var line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
    
        line.setAttribute('x1', '0');
        line.setAttribute('x2', '0');
        line.setAttribute('x2', '20');
        line.setAttribute('y2', '20');
    
        line.setAttribute('style', 'stroke: {{color}};');
    
        svgEle.append($compile(line)($scope));
      }
    ]);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <div ng-app="actApp">
    <div ng-controller="shapeController">
      <input type="button" ng-click="color='blue'" value="To blue" />
    
      <br />
    
      <svg id="mySvgElement" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0" y="0" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve">
    
      </svg>
    
    </div>
      </div>

    希望这可以为将来节省一些时间。

    【讨论】:

      猜你喜欢
      • 2018-02-24
      • 2015-11-10
      • 1970-01-01
      • 1970-01-01
      • 2019-03-30
      • 2017-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多