【问题标题】:Using Angular ng-class with d3.js on svg element在 svg 元素上使用 Angular ng-class 和 d3.js
【发布时间】:2018-02-27 01:58:48
【问题描述】:

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

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

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

但没有任何效果。

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

【问题讨论】:

    标签: javascript angularjs d3.js svg ng-class


    【解决方案1】:

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

    Angular 不会自动监听这个属性。您必须在生成的 svg 上调用 $compile(svg)($scope),这样 Angular 才能发挥其“魔力”。

    $compile Angular Service

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

    Working JS fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-08
      • 2017-01-20
      • 2016-04-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-15
      • 2016-07-28
      • 2015-02-17
      相关资源
      最近更新 更多