在SVG元素上使用Angular ng-class和d3.js

3
尝试在SVG元素上使用angular ng-classd3js库,但没有成功。
HTML
<div ng-controller="MainCtrl">

  <div id="svgContainer"></div>
  <button id="swicthBtn" ng-click="switchStatus();" class="btn">Switch status</button>

</div>

CSS

*, *:before, *:after {
  bounding-box: border-box;
}

#svgContainer {
  width: 400px;
  height: 400px;
  background-color: #333;
}

.btn {
  margin: 1em;
  padding: 1em;
}

.active {
  fill: red;
}

.inactive {
  fill: #666;
}

JS

var app = angular.module("myApp", []);

app.controller("MainCtrl", ["$scope", function($scope) {

    $scope.status = true;
  $scope.switchStatus = function() {
    $scope.status = !$scope.status;
  }

  var svg = d3.select("#svgContainer").append("svg")
    .attr("width", 400)
    .attr("height", 400);

  var rect = svg.append("rect")
    .attr("x", 150)
    .attr("y", 150)
    .attr("width", 100)
    .attr("height", 100)
    .attr("ng-class", "status ? 'active' : 'inactive'");

}]);

这是jsfiddle。 有两个CSS类,active和inactive,我想根据$scope.status变量的值动态地分配给svg矩形。实际上它不起作用。我尝试了一些ng-class表达式的变化,比如:

"{status ? 'active' : 'inactive'}" 

或者

"{'status' ? 'active' : 'inactive'}" 

但是没有一个有效。

ng-class指令在svg元素上不受支持,还是我做错了什么?

1个回答

3
您正在尝试在未通过angular编译的情况下将ng-class用作属性。
Angular不会自动监听此属性。您必须在生成的svg上调用$compile(svg)($scope),以便angular执行其“魔法”。
还要确保在dom元素上调用angular,而不是包装后的d3元素。 $compile Angular Service Working JS fiddle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接