在angularJs项目中使用到了svg,发现在svg中不可以像其他的元素上一样使用angularJs的指令,而是需要以ng-attr的形式来使用angularJs的指令。
1、如果按和其他元素一样的方法去使用指令会报错
<!--错误写法-->
<line x1="{{line.x1}}" y1="{{line.y1}}" x2="{{line.x2}}" y2="{{line.y2}}"
ng-repeat="line in lineList track by $index"></line>
会报如下地错误:
2、正确的使用方法
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
<script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
<style>
.svgBox {
width: 500px;
height: 500px;
}
</style>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl" class="svgBox">
<svg>
<line ng-attr-x1="{{line.x1}}" ng-attr-y1="{{line.y1}}" ng-attr-x2="{{line.x2}}" ng-attr-y2="{{line.y2}}"
ng-repeat="line in lineList track by $index" style="stroke-width: 2px;stroke:#f00;"></line>
</svg>
</div>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.lineList = [{
x1: 200,
y1: 30,
x2: 30,
y2: 30,
},
{
x1: 20,
y1: 20,
x2: 300,
y2: 300,
},
]
});
</script>
</body>
</html>
显示结果: