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

Using Angular ng-class with d3.js on svg element

尝试使用 angular ng-class with d3js library on an svg 元素,但没有成功。

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。 有 2 css classes,活动和非活动,我想根据 $scope.status 变量的值动态分配给 svg rect。实际上这是行不通的。我尝试了 ng-class 表达式的一些变体,例如:

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

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

但 none 有效。

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

您正在尝试使用 ng-class 作为属性,而不是先通过 angular 编译它。

Angular 不会自动侦听此属性。您必须在生成的 svg 上调用 $compile(svg)($scope),因此 angular 将执行其 "magic".

$compile Angular Service

还要确保在 dom 元素而不是包装的 d3 元素上调用 angular。

Working JS fiddle