在运行时以2种方式绑定角度添加svg元素 [英] add svg element at runtime in angular with 2 way data binding

查看:67
本文介绍了在运行时以2种方式绑定角度添加svg元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to add svg element line at runtime with ng-attr-x1={{some scope varaible}}. I tried 2 ways: In 1 way I tried with $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.

In this method line is not showing and g is showing with 0px height and width.

我以两种方式恐慌:

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中,它显示为

In this ng-attr attributes does not resolved to x and y. In DOM it shows as

推荐答案

这可能为时已晚,无法为您提供帮助,但是我在同一个问题上停留了一段时间.

This is possibly coming in way too late to help you, but I was stuck for a little while on the same question.

结果是$ compile可以接受用document.createElementNS()创建的元素-像这样:

Turns out that $compile can take an element created with document.createElementNS() - like this:

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>

希望这可以为以后节省一些时间.

Hope this saves someone a little bit of time in the future.

这篇关于在运行时以2种方式绑定角度添加svg元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆