revy
revy

Reputation: 4707

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

Trying to use angular ng-class with d3js library on an svg element, without luck.

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'");

}]);

This is the jsfiddle. There 2 css classes, active and inactive, which I would like to assign to the svg rect dynamically based on the value of the $scope.status variable. Actually it doesn't work. I tried some variations on the ng-class expression like:

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

or

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

but none worked.

Is the ng-class directive unsupported on svg elements or am I doing something wrong?

Upvotes: 3

Views: 1219

Answers (1)

PiniH
PiniH

Reputation: 1941

You are trying to use ng-class as an attribute without compiling it via angular first.

Angular doesn't automatically listen for this attribute. You'd have to call $compile(svg)($scope) on the resulting svg so angular will do its "magic".

$compile Angular Service

Also make sure to call angular on the dom element and not on the wrapped d3 element.

Working JS fiddle

Upvotes: 3

Related Questions