angular ng-class & d3.js

by Revy Twohands

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.2/d3.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<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;
}

JavaScript

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