Skip to content

Instantly share code, notes, and snippets.

@rubyonrailstutor
Last active December 25, 2015 02:39
Show Gist options
  • Save rubyonrailstutor/6904104 to your computer and use it in GitHub Desktop.
Save rubyonrailstutor/6904104 to your computer and use it in GitHub Desktop.
d3 stuff
angular.module('CrowdSound').directive 'csPie', () ->
restrict: "E"
scope:
question: "="
index: "="
link: (scope, element, attrs) ->
scope.data = []
class PieChart
constructor: (element, data) ->
@width = 300
@height = 300
@oRadius = @width/2
@iRadius = 50
@padding = 50
@data = [1,2,3]
@layout = d3.layout.pie()
@chart = d3.select(element[0])
@pieChart = @chart.append("svg")
.attr("width", @width)
.attr("height", @height)
@wedges = @pieChart.selectAll("g")
.data(@layout(@data))
.enter()
.append("g")
.attr("class" : "wedge")
.attr("transform", "translate(" + @oRadius + "," + @oRadius + ")" )
@arc = d3.svg.arc()
.innerRadius(@iRadius)
.outerRadius(@oRadius)
@color = d3.scale.category10().domain(d3.range(0,10))
draw: () ->
@wedges.selectAll("path")
.data(@layout(@data))
.enter()
.append("path")
.attr('fill', (d,i) => @color(i))
.attr('d', @arc)
show: () ->
console.log "chart", @chart
console.log "data", @data
console.log "pieChart", @pieChart
refreshData: (data) ->
console.log "data", data
@data = data
console.log "@data", @data
console.log "scope.data", scope.data
createLabels: () ->
@labels = @wedges.append("text")
.attr('transform',
(d) =>
'translate(' + @arc.centroid(d) + ')' )
.attr('text-anchor', 'middle')
.text((d) -> d.value)
pieChart = new PieChart(element, scope.data)
pieChart.draw()
pieChart.show()
pieChart.createLabels()
# @reDraw = (newData) ->
# wedges.selectAll("g")
# wedges.data( layout()(newData) )
# .enter()
# .append("g")
# .attr("class" : "wedge")
# .attr("transform", "translate(" + oRadius + "," + oRadius + ")" )
# .append("path")
# .attr('fill', (d,i) => color()(i))
# .attr('d', arc)
# wedges.select('path')
# .transition()
# .duration(1000)
# .ease('bounce')
# .attr('fill', (d,i) => color()(i))
# .attr('d', arc)
# labels.data( layout()(newData))
# .transition()
# .duration(1000)
# .attr('transform', (d) => 'translate(' + arc.centroid(d) + ')' )
# .attr('text-anchor', 'middle')
# .text((d) => d)
scope.$watch "data",
(newData, oldData) =>
if newData
pieChart.refreshData(newData)
pieChart.draw()
,
true
scope.$watch 'question',
(newData, oldData) ->
if newData
console.log "new questions received"
rawData = []
_.each newData.answers, (obj) ->
if obj.votes?
rawData.push obj.votes
scope.data = rawData
,
true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment