How to call d3 pie chart on button click in angularjs? - angularjs

I am trying to display pie chart using d3.js charts in angularjs . As far as the examples i have seen so far implements pie chart on load . But here i want to display pie chart based on the response from service which is called on a button click . Need some guidance to start
my user.html
<h1>Group by users</h1><br>
<select name="users" id="search" ng-model="searchItem">
<option value="">Search By</option>
<option value="admin">admin</option>
<option value="superAdmin">superAdmin</option>
</select>
<button ng-click="search()">Search</button>
<div pie-chart="" style="width:100%;height:460px;" data="data"></div>
my user.js
'use strict';
angular.module('myApp.employee',['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/employee', {
templateUrl: 'employee/employee.html',
controller: 'EmployeeCtrl'
});
}])
.controller('EmployeeCtrl', ['$scope','$http',function($scope,$http) {
$scope.search = function(){
var search=angular.element(document.getElementById("search"));
//var data ;
$scope.searchItem =search.val();
console.log($scope.searchItem);
$http.get("/assets/empDetails.json").then(function(response){
// $scope.empDetail=response.data
console.log(response.data);
console.log();
// function groupBy(arr, prop) {
// const map = new Map(Array.from(arr, obj => [obj[prop], []]));
// arr.forEach(obj => map.get(obj[prop]).push(obj));
// return Array.from(map.values());
// }
// console.log(groupBy(response.data,$scope.searchItem ));
var rows = response.data;
var keyName =$scope.searchItem;
groupBy(keyName);
function groupBy(keyName) {
console.log("Group By :: ", keyName)
var occurences = rows.reduce(function (r, row) {
r[row[keyName]] = ++r[row[keyName]] || 1;
return r;
}, {});
var result = Object.keys(occurences).map(function (key) {
return { key: key, value: occurences[key] };
});
console.log(result);
//data = result ;
$scope.data = [
{
name : "Blue",
value : 10,
color : "#4a87ee"
},
{
name : "Green",
value : 40,
color : "#66cc33"
},
{
name : "Orange",
value : 70,
color : "#f0b840"
},
{
name : "Red",
value : 2,
color : "#ef4e3a"
}
];
}
})
}
}])
.directive ("pieChart", function () {
return {
restrict : "A",
scope : {
data : "="
},
link : function (scope, element) {
var width,
height,
radius,
pie,
arc,
svg,
path;
width = element[0].clientWidth;
height = element[0].clientHeight;
radius = Math.min (width, height) / 2;
pie = d3.layout.pie ()
.value (function (d) {return d.value;})
.sort (null);
arc = d3.svg.arc ()
.outerRadius (radius - 20)
.innerRadius (radius - 80);
svg = d3.select (element[0])
.append ("svg")
.attr ({width : width, height : height})
.append ("g")
.attr ("transform", "translate(" + width * 0.5 + "," + height * 0.5 + ")");
path = svg.datum (scope.data)
.selectAll ("path")
.data (pie)
.enter ()
.append ("path")
.attr ({
fill : function (d, i) {return scope.data [i].color;},
d : arc
});
scope.$watch (
"data",
function () {
pie.value (function (d) {return d.value;});
path = path.data(pie);
path.attr("d", arc);
},
true
);
}
};
})
i have used this https://embed.plnkr.co/plunk/jDvdSh as reference . All i want to implement is on search i want perform the service call and then manipulate the response and render it as a pie chart.or someone please explain how the pie chart directive is called in the above plnkr reference that would be more helpful

Related

D3 tween does not work inside angular

I'm working on this example:
http://bl.ocks.org/mbostock/7607535
I wrapped this into a directive. For some reason, the tween method does not get fired.
var transition = d3.transition()
.duration(d3.event.altKey ? 7500 : 750)
.tween("zoom", function(d) {
var i = d3.interpolateZoom(view, [focus.x, focus.y, focus.r * 2 + margin]);
return function(t) { zoomTo(i(t)); };
});
Is tween incompatible with angular ? Any idea where I should start looking ?
I made a small fiddle from the above http://bl.ocks.org/mbostock/7607535.
I have incorporated the d3 svg component via directive and the tween works perfectly.
var app = angular.module('myApp', []);
app.controller('myController', ['$scope', function ($scope) {
$scope.myData = {"name":"flare","children":[{"name":"analytics","children":[{"name":"cluster","children":[{"name":"AgglomerativeCluster","size":3938},{"name":"CommunityStructure","size":3812},{"name":"HierarchicalCluster","size":6714},{"name":"MergeEdge","size":743}]},{"name":"graph","children":[{"name":"BetweennessCentrality","size":3534},{"name":"LinkDistance","size":5731},{"name":"MaxFlowMinCut","size":7840},{"name":"ShortestPaths","size":5914},{"name":"SpanningTree","size":3416}]},{"name":"optimization","children":[{"name":"AspectRatioBanker","size":7074}]}]},{"name":"animate","children":[{"name":"Easing","size":17010},{"name":"FunctionSequence","size":5842},{"name":"interpolate","children":[{"name":"ArrayInterpolator","size":1983},{"name":"ColorInterpolator","size":2047},{"name":"DateInterpolator","size":1375},{"name":"Interpolator","size":8746},{"name":"MatrixInterpolator","size":2202},{"name":"NumberInterpolator","size":1382},{"name":"ObjectInterpolator","size":1629},{"name":"PointInterpolator","size":1675},{"name":"RectangleInterpolator","size":2042}]},{"name":"ISchedulable","size":1041},{"name":"Parallel","size":5176},{"name":"Pause","size":449},{"name":"Scheduler","size":5593},{"name":"Sequence","size":5534},{"name":"Transition","size":9201},{"name":"Transitioner","size":19975},{"name":"TransitionEvent","size":1116},{"name":"Tween","size":6006}]},{"name":"data","children":[{"name":"converters","children":[{"name":"Converters","size":721},{"name":"DelimitedTextConverter","size":4294},{"name":"GraphMLConverter","size":9800},{"name":"IDataConverter","size":1314},{"name":"JSONConverter","size":2220}]},{"name":"DataField","size":1759},{"name":"DataSchema","size":2165},{"name":"DataSet","size":586},{"name":"DataSource","size":3331},{"name":"DataTable","size":772},{"name":"DataUtil","size":3322}]},{"name":"display","children":[{"name":"DirtySprite","size":8833},{"name":"LineSprite","size":1732},{"name":"RectSprite","size":3623},{"name":"TextSprite","size":10066}]},{"name":"flex","children":[{"name":"FlareVis","size":4116}]},{"name":"physics","children":[{"name":"DragForce","size":1082},{"name":"GravityForce","size":1336},{"name":"IForce","size":319},{"name":"NBodyForce","size":10498},{"name":"Particle","size":2822},{"name":"Simulation","size":9983},{"name":"Spring","size":2213},{"name":"SpringForce","size":1681}]},{"name":"query","children":[{"name":"AggregateExpression","size":1616},{"name":"And","size":1027},{"name":"Arithmetic","size":3891},{"name":"Average","size":891},{"name":"BinaryExpression","size":2893},{"name":"Comparison","size":5103},{"name":"CompositeExpression","size":3677},{"name":"Count","size":781},{"name":"DateUtil","size":4141},{"name":"Distinct","size":933},{"name":"Expression","size":5130},{"name":"ExpressionIterator","size":3617},{"name":"Fn","size":3240},{"name":"If","size":2732},{"name":"IsA","size":2039},{"name":"Literal","size":1214},{"name":"Match","size":3748},{"name":"Maximum","size":843},{"name":"methods","children":[{"name":"add","size":593},{"name":"and","size":330},{"name":"average","size":287},{"name":"count","size":277},{"name":"distinct","size":292},{"name":"div","size":595},{"name":"eq","size":594},{"name":"fn","size":460},{"name":"gt","size":603},{"name":"gte","size":625},{"name":"iff","size":748},{"name":"isa","size":461},{"name":"lt","size":597},{"name":"lte","size":619},{"name":"max","size":283},{"name":"min","size":283},{"name":"mod","size":591},{"name":"mul","size":603},{"name":"neq","size":599},{"name":"not","size":386},{"name":"or","size":323},{"name":"orderby","size":307},{"name":"range","size":772},{"name":"select","size":296},{"name":"stddev","size":363},{"name":"sub","size":600},{"name":"sum","size":280},{"name":"update","size":307},{"name":"variance","size":335},{"name":"where","size":299},{"name":"xor","size":354},{"name":"_","size":264}]},{"name":"Minimum","size":843},{"name":"Not","size":1554},{"name":"Or","size":970},{"name":"Query","size":13896},{"name":"Range","size":1594},{"name":"StringUtil","size":4130},{"name":"Sum","size":791},{"name":"Variable","size":1124},{"name":"Variance","size":1876},{"name":"Xor","size":1101}]},{"name":"scale","children":[{"name":"IScaleMap","size":2105},{"name":"LinearScale","size":1316},{"name":"LogScale","size":3151},{"name":"OrdinalScale","size":3770},{"name":"QuantileScale","size":2435},{"name":"QuantitativeScale","size":4839},{"name":"RootScale","size":1756},{"name":"Scale","size":4268},{"name":"ScaleType","size":1821},{"name":"TimeScale","size":5833}]},{"name":"util","children":[{"name":"Arrays","size":8258},{"name":"Colors","size":10001},{"name":"Dates","size":8217},{"name":"Displays","size":12555},{"name":"Filter","size":2324},{"name":"Geometry","size":10993},{"name":"heap","children":[{"name":"FibonacciHeap","size":9354},{"name":"HeapNode","size":1233}]},{"name":"IEvaluable","size":335},{"name":"IPredicate","size":383},{"name":"IValueProxy","size":874},{"name":"math","children":[{"name":"DenseMatrix","size":3165},{"name":"IMatrix","size":2815},{"name":"SparseMatrix","size":3366}]},{"name":"Maths","size":17705},{"name":"Orientation","size":1486},{"name":"palette","children":[{"name":"ColorPalette","size":6367},{"name":"Palette","size":1229},{"name":"ShapePalette","size":2059},{"name":"SizePalette","size":2291}]},{"name":"Property","size":5559},{"name":"Shapes","size":19118},{"name":"Sort","size":6887},{"name":"Stats","size":6557},{"name":"Strings","size":22026}]}]}
}]);
app.directive('packChart', function () {
return {
restrict: 'EA',
link: function (scope, elem, attrs) {
var root = scope.myData;
var margin = 20,
diameter = 960;
var color = d3.scale.linear()
.domain([-1, 5])
.range(["hsl(152,80%,80%)", "hsl(228,30%,40%)"])
.interpolate(d3.interpolateHcl);
var pack = d3.layout.pack()
.padding(2)
.size([diameter - margin, diameter - margin])
.value(function (d) {
return d.size;
})
var svg = d3.select("svg")
.attr("width", diameter)
.attr("height", diameter)
.append("g")
.attr("transform", "translate(" + diameter / 2 + "," + diameter / 2 + ")");
var focus = root,
nodes = pack.nodes(root),
view;
var circle = svg.selectAll("circle")
.data(nodes)
.enter().append("circle")
.attr("class", function (d) {
return d.parent ? d.children ? "node" : "node node--leaf" : "node node--root";
})
.style("fill", function (d) {
return d.children ? color(d.depth) : null;
})
.on("click", function (d) {
if (focus !== d) zoom(d), d3.event.stopPropagation();
});
var text = svg.selectAll("text")
.data(nodes)
.enter().append("text")
.attr("class", "label")
.style("fill-opacity", function (d) {
return d.parent === root ? 1 : 0;
})
.style("display", function (d) {
return d.parent === root ? null : "none";
})
.text(function (d) {
return d.name;
});
var node = svg.selectAll("circle,text");
d3.select("body")
.style("background", color(-1))
.on("click", function () {
zoom(root);
});
zoomTo([root.x, root.y, root.r * 2 + margin]);
function zoom(d) {
var focus0 = focus;
focus = d;
var transition = d3.transition()
.duration(d3.event.altKey ? 7500 : 750)
.tween("zoom", function (d) {
var i = d3.interpolateZoom(view, [focus.x, focus.y, focus.r * 2 + margin]);
return function (t) {
zoomTo(i(t));
};
});
transition.selectAll("text")
.filter(function (d) {
return d.parent === focus || this.style.display === "inline";
})
.style("fill-opacity", function (d) {
return d.parent === focus ? 1 : 0;
})
.each("start", function (d) {
if (d.parent === focus) this.style.display = "inline";
})
.each("end", function (d) {
if (d.parent !== focus) this.style.display = "none";
});
}
function zoomTo(v) {
var k = diameter / v[2];
view = v;
node.attr("transform", function (d) {
return "translate(" + (d.x - v[0]) * k + "," + (d.y - v[1]) * k + ")";
});
circle.attr("r", function (d) {
return d.r * k;
});
}
}
};
});
.node {
cursor: pointer;
}
.node:hover {
stroke: #000;
stroke-width: 1.5px;
}
.node--leaf {
fill: white;
}
.label {
font: 11px"Helvetica Neue", Helvetica, Arial, sans-serif;
text-anchor: middle;
text-shadow: 0 1px 0 #fff, 1px 0 0 #fff, -1px 0 0 #fff, 0 -1px 0 #fff;
}
.label, .node--root, .node--leaf {
pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div ng-app='myApp' ng-controller="myController">
<h1>My Chart</h1>
<svg pack-chart></svg>
</div>
Working code here
Hope this helps!
The root of the problem was datejs. Once I removed it, D3 transitions work fine.

nvd3 pie chart when no data and for value zero

I have created a pie chart using nvd3.
Here is my code :
<nvd3-pie-chart
data="examplePieData"
id="exampleId"
showLabels="true"
labelType="value"
x="xPieFunction()"
y="yPieFunction()"
donut="true"
donutRatio=".5"
tooltips="true"
noData="Data aint here"
tooltipcontent="toolTipContentFunction()"
color="pieColorFunction()"
donutLabelsOutside="false">
<svg height="200" style="margin-left: -121px; margin-top: -49px;"></svg>
</nvd3-pie-chart>
and
$scope.examplePieData = [
{
key: "First",
y: 5
},
{
key: "Second",
y: 3
},
{
key: "Third",
y: 1
}
];
$scope.toolTipContentFunction = function(){
return function(key, x, y, e, graph) {
return '<p>' + key +" "+ y.value + '</p>'
}
}
$scope.xPieFunction = function(){
return function(d) {
return d.key;
};
}
$scope.yPieFunction = function(){
return function(d) {
return d.y;
};
}
var pieColorArray = [ '#5EA9DD','#e76060', '#008000'];
$scope.pieColorFunction = function() {
return function(d, i) {
return pieColorArray[i];
};
}
Here I want to display a message when there is no data. I have tried with noDate = "Message" but it is not working. And I want to show pic chart even for y value is zero (y :0). Finally, how to adjust tooltip distance and same color for the tooltip when mouseover on the perticular field in pie chart. Help me. Thank you.
For no data, try with chart.noData() function. For me it is perfectly working,
HTML:
<div id="chart">
<svg></svg>
</div>
Javascript:
var h = 300;
var r = h/2;
var data = [];
var colors = [
'rgb(178, 55, 56)',
'rgb(213, 69, 70)',
'rgb(230, 125, 126)',
'rgb(239, 183, 182)'
];
nv.addGraph(function() {
var chart = nv.models.pieChart()
.x(function(d) { return d.label })
.y(function(d) { return d.value })
.color(colors)
.showLabels(true)
.labelType("percent");
chart.noData("No data");
d3.select("#chart svg")
.datum(data)
.transition().duration(1200)
.call(chart)
;
return chart;
});

Trying to create D3 + AngularJS Bar Chart

I would like to create a D3 Bar chart with angularjs. This is my directive, and currently I am having a couple of problems.
The chart is not appended to the directives div, but to html tag
Chart is appended multiple times, even though when watch is called, we only log one append
When loggin d3.select(jqElm[0]), it outputs the directives element
What am I doing wrong?
(function (angular, d3) {
'use strict';
var isDef = angular.isDefined,
aExtend = angular.extend,
aCopy = angular.copy,
isArray = angular.isArray,
isObject = angular.isObject,
aElement = angular.element,
isEqual = angular.equals;
angular.module('Widgets.Module')
.factory('ConstructorD3Bar', Constructor)
.directive('tmD3Bar', Directive);
Constructor.$inject = [
'Common'
];
Directive.$inject = [
'Common',
'ConstructorD3Bar'
];
function Constructor(Common) {
var cgenerator = Common.Generator;
function D3Bar(attrs) {
this._setProps(attrs);
}
D3Bar.prototype = {
_setProps: function (p) {
p = p || {};
this.id = isDef(p.id) ? p.id : cgenerator.id;
this.theme = isDef(p.theme) ? p.theme : 'D3Bar';
this.message = isDef(p.message) ? p.message : 'D3Bar';
this.data = isDef(p.data) ? p.data : [];
this.format = isDef(p.format) ? p.format : null;
this.tsv = isDef(p.tsv) ? p.tsv : null;
this.csv = isDef(p.csv) ? p.csv : null;
this.margin = isDef(p.margin) ? p.margin : { top: 0, bottom: 0, left: 0, right: 0};
this.boxWidth = isDef(p.boxWidth) ? p.boxWidth : Common.$window.innerWidth;
this.boxHeight = isDef(p.boxHeight) ? p.boxHeight : Common.$window.innerHeight;
this.width = isDef(p.width) ? p.width : Common.$window.innerWidth;
this.height = isDef(p.height) ? p.height : Common.$window.innerHeight;
this.init();
},
init: function () {
var that = this;
if (that.tsv !== null) {
d3.tsv(that.tsv, function (err, data) {
if (isDef(err) && err && err.status) {
switch (err.status) {
case 404:
return;
}
}
that.data = data;
});
}
},
toString: function () {
return this;
}
};
return {
create: function (props) {
return new D3Bar(props);
}
};
}
function Directive(
Common,
ConstructorD3Bar
) {
var directive = {
templateUrl: 'widgets/d3-charts/bar/bar.tpl.html',
controller: ctrl,
compile: compile,
scope: {
attrs: '=?'
},
replace: true,
restrict: 'AC'
};
return directive;
function compile(tElement, tAttrs) {
return {
pre: function (scope, jqElm, attr) {
scope.initWidget = function () {
if (!isDef(scope.attrs) || scope.attrs === null) {
scope.attrs = ConstructorD3Bar.create({});
}
var margin = scope.attrs.margin,
width = scope.attrs.boxWidth - margin.left - margin.right,
height = scope.attrs.boxHeight - margin.top - margin.bottom;
scope.attrs.width = width;
scope.attrs.height = height;
var formatPercent = d3.format('.0%');
scope.attrs.x = d3.scale
.ordinal()
.rangeRoundBands([0, width], 0.1, 1);
scope.attrs.y = d3.scale
.linear()
.range([height, 0]);
scope.attrs.xAxis = d3.svg
.axis()
.scale(scope.attrs.x)
.orient('bottom');
scope.attrs.yAxis = d3.svg
.axis()
.scale(scope.attrs.y)
.orient('left')
.tickFormat(formatPercent);
};
},
post: function (scope, jqElm, attr) {
scope.$on('$destroy', function () { });
scope.$watch(
function () {
return scope.attrs.data;
},
function (nValue, oValue) {
if (!nValue) {
return;
}
if (nValue.length === 0) {
return;
}
var data = nValue;
scope.attrs.svg = d3.select(jqElm[0])
.data(data)
.enter()
.append('svg')
.attr('width', scope.attrs.width + scope.attrs.margin.left + scope.attrs.margin.right)
.attr('height', scope.attrs.height + scope.attrs.margin.top + scope.attrs.margin.bottom)
.append('g')
.attr('transform', 'translate(' + scope.attrs.margin.left + ',' + scope.attrs.margin.top + ')');
data.forEach(function (d) {
d.frequency = +d.frequency;
});
scope.attrs.x.domain(data.map(function (d) {
return d.letter;
}));
scope.attrs.y.domain([0, d3.max(data, function (d) {
return d.frequency;
})]);
scope.attrs.svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + scope.attrs.height + ')')
.call(scope.attrs.xAxis);
scope.attrs.svg.append('g')
.attr('class', 'y axis')
.call(scope.attrs.yAxis)
.append('text')
.attr('transform', 'rotate(-90)')
.attr('y', 6)
.attr('dy', '.71em')
.style('text-anchor', 'end')
.text('Frequency');
scope.attrs.svg.selectAll('.bar')
.data(data)
.enter().append('rect')
.attr('class', 'bar')
.attr('x', function (d) {
return scope.attrs.x(d.letter);
})
.attr('width', scope.attrs.x.rangeBand())
.attr('y', function (d) {
return scope.attrs.y(d.frequency);
})
.attr('height', function (d) {
return scope.attrs.height - scope.attrs.y(d.frequency);
});
}
);
}
};
}
function ctrl($scope, $element, $attrs) {
var vm = $scope;
if (!isDef(vm.attrs) || vm.attrs === null) {
vm.attrs = ConstructorD3Bar.create({ });
}
var attrs = vm.attrs;
}
}
})(window.angular, window.d3);
<div id="{{ attrs.id }}" class="D3Bar" ng-class="attrs.theme" ng-init="initWidget()">
</div>
Remove .data().enter in .select
scope.attrs.svg = d3.select(jqElm[0])
.append('svg')
.attr('width', scope.attrs.width + scope.attrs.margin.left + scope.attrs.margin.right)
.attr('height', scope.attrs.height + scope.attrs.margin.top + scope.attrs.margin.bottom)
.append('g')
.attr('transform', 'translate(' + scope.attrs.margin.left + ',' + scope.attrs.margin.top + ')');

Angular d3 donut

I am trying to make a donut chart using d3 and angular however, I am stuck.Should I add all d3 code to function link or is there any other way? Moreover, I want this chart to be dynamic.
Here is the code for my directive:
angular.module('d3onut',[])
.directive('donut', function (){
function link(scope, elements, attr){
var data = scope.data;
};
return {
restrict: EA,
replace: true,
link : link,
scope: { data '='}
}
})
This is the d3 code, it mostly works but, any help in making it better is welcome
var data = [{
name: "one",
value: 75
}, {
name: "two",
value: 25
}, ];
var width = 100;
height = width;
var chart = d3.select("#circle-4")
.append('svg')
.attr("width", width)
.attr("height", height)
.append("gh")
.attr("transform", "translate(" + (width / 2) + "," + (height / 2) + ")");
var radius = Math.min(width, height) / 2;
var arc = d3.svg.arc()
.outerRadius(radius / 2)
.innerRadius(radius - 15);
var pie = d3.layout.pie()
.sort(null)
.startAngle(0)
.endAngle(2 * Math.PI)
.value(function (d) {
return d.value;
});
var color = d3.scale.ordinal()
.range(["#3399FF", "#e1e1e1"]);
var gh = chart.selectAll(".arc")
.data(pie(data))
.enter().append("gh")
.attr("class", "arc");
gh.append("path")
.attr("fill", function (d, i) {
return color(i);
})
.transition()
.ease("exp")
.duration(1000)
.attrTween("d", dpie);
function dpie(b) {
var i = d3.interpolate({
startAngle: 0,
endAngle: 1 * Math.PI
}, b);
return function (t) {
return arc(i(t));
};
}
Yes using the link is fine. You shluld use scope.$watch to watch for changes in your scope. This is a good tutorial.
http://www.ng-newsletter.com/posts/d3-on-angular.html

How to draw a d3.js line chart using angularjs directives

How to use angular directives to load the d3.js graph using scope json data instead of using graph.html file.I had referred this urlurl.But unable to do it for line chart.
Can anyone please help me out regarding this issue ...
My graph.html:
function getDate(d) {
var dt = new Date(d.date);
dt.setHours(0);
dt.setMinutes(0);
dt.setSeconds(0);
dt.setMilliseconds(0);
return dt;
}
function showData(obj, d) {
var coord = d3.mouse(obj);
var infobox = d3.select(".infobox");
// now we just position the infobox roughly where our mouse is
infobox.style("left", (coord[0] + 100) + "px" );
infobox.style("top", (coord[1] - 175) + "px");
$(".infobox").html(d);
$(".infobox").show();
}
function hideData() {
$(".infobox").hide();
}
var drawChart = function(data) {
// define dimensions of graph
var m = [10, 20, 10, 50]; // margins
var w = 250 - m[1] - m[3]; // width
var h = 100 - m[0] - m[2]; // height
data.sort(function(a, b) {
var d1 = getDate(a);
var d2 = getDate(b);
if (d1 == d2) return 0;
if (d1 > d2) return 1;
return -1;
});
var minDate = getDate(data[0]),
maxDate = getDate(data[data.length-1]);
var x = d3.time.scale().domain([minDate, maxDate]).range([0, w]);
var y = d3.scale.linear().domain([0, d3.max(data, function(d) { return d.trendingValue; } )]).range([h, 0]);
var line = d3.svg.line()
.x(function(d, i) {
return x(getDate(d)); //x(i);
})
.y(function(d) {
return y(d.trendingValue);
});
function xx(e) { return x(getDate(e)); };
function yy(e) { return y(e.trendingValue); };
var graph = d3.select("#chart").append("svg:svg")
.attr("width", w + m[1] + m[3])
.attr("height", h + m[0] + m[2])
.append("svg:g")
.attr("transform", "translate(" + m[3] + "," + m[0] + ")");
var xAxis = d3.svg.axis().scale(x).ticks(d3.time.months, 1).tickSize(-h).tickSubdivide(true);
var yAxisLeft = d3.svg.axis().scale(y).ticks(10).orient("left"); //.tickFormat(formalLabel);
graph
.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("fill", "steelblue")
.attr("r", 5)
.attr("cx", xx)
.attr("cy", yy)
.on("mouseover", function(d) { showData(this, d.trendingValue);})
.on("mouseout", function(){ hideData();});
graph.append("svg:path").attr("d", line(data));
$("#chart").append("<div class='infobox' style='display:none;'>Test</div>");
}
My directive:(which I had tried but unable to draw a graph)
angular.module( 'chart').directive( 'crD3Bars', [
function () {
return {
restrict: 'E',
scope: {
data: '='
},
link: function (scope, element) {
function getDate(d) {
var dt = new Date(d.date);
dt.setHours(0);
dt.setMinutes(0);
dt.setSeconds(0);
dt.setMilliseconds(0);
return dt;
}
function showData(obj, d) {
var coord = d3.mouse(obj);
var infobox = d3.select(".infobox");
// now we just position the infobox roughly where our mouse is
infobox.style("left", (coord[0] + 100) + "px" );
infobox.style("top", (coord[1] - 175) + "px");
$(".infobox").html(d);
$(".infobox").show();
}
function hideData() {
$(".infobox").hide();
}
var drawChart = function(data) {
// define dimensions of graph
var m = [10, 20, 10, 50]; // margins
var w = 250 - m[1] - m[3]; // width
var h = 100 - m[0] - m[2]; // height
data.sort(function(a, b) {
var d1 = getDate(a);
var d2 = getDate(b);
if (d1 == d2) return 0;
if (d1 > d2) return 1;
return -1;
});
var minDate = getDate(data[0]),
maxDate = getDate(data[data.length-1]);
var x = d3.time.scale().domain([minDate, maxDate]).range([0, w]);
var y = d3.scale.linear().domain([0, d3.max(data, function(d) { return d.trendingValue; } )]).range([h, 0]);
var line = d3.svg.line()
.x(function(d, i) {
return x(getDate(d)); //x(i);
})
.y(function(d) {
return y(d.trendingValue);
});
function xx(e) { return x(getDate(e)); };
function yy(e) { return y(e.trendingValue); };
var graph = d3.select("#chart").append("svg:svg")
.attr("width", w + m[1] + m[3])
.attr("height", h + m[0] + m[2])
.append("svg:g")
.attr("transform", "translate(" + m[3] + "," + m[0] + ")");
var xAxis = d3.svg.axis().scale(x).ticks(d3.time.months, 1).tickSize(-h).tickSubdivide(true);
var yAxisLeft = d3.svg.axis().scale(y).ticks(10).orient("left"); //.tickFormat(formalLabel);
graph
.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("fill", "steelblue")
.attr("r", 5)
.attr("cx", xx)
.attr("cy", yy)
.on("mouseover", function(d) { showData(this, d.trendingValue);})
.on("mouseout", function(){ hideData();});
graph.append("svg:path").attr("d", line(data));
$("#graphDiv3").append("<div class='infobox' style='display:none;'>Test</div>");
}
drawchart(data);
}
};
}
]);
Instead of mashing up two blocks of code and hoping it works, I'd recommend you follow some simple angular tutorials to get a better grasp of the basics. Also, some simple debugging would have gone a long way here.
You do not declare your module.
You do not seem to pass in your data anywhere (like in a controller which also doesn't exist).
The function is drawChart, you are calling drawchart
In your directive, you select a div with id of chart, this doesn't exist. Since it's a directive and they act on elements use d3.select(element[0])
All that said once you work through these relatively simple mistakes, you get some working code:
var myAppModule = angular.module('chart', []);
angular.module('chart').controller('chartCtrl', function ($scope) {
$scope.myData = [{
"date": "2015-10-01",
"trendingValue": "244"
},
{
"date": "2015-07-01",
"trendingValue": "0"
},
{
"date": "2015-06-01",
"trendingValue": "117"
},
{
"date": "2015-05-01",
"trendingValue": "5353"
},
{
"date": "2015-04-01",
"trendingValue": "11159"
},
{
"date": "2015-03-01",
"trendingValue": "7511"
},
{
"date": "2015-02-01",
"trendingValue": "6906"
},
{
"date": "2015-01-01",
"trendingValue": "10816"
},
{
"date": "2014-12-01",
"trendingValue": "3481"
},
{
"date": "2014-11-01",
"trendingValue": "1619"
},
{
"date": "2014-10-01",
"trendingValue": "4084"
},
{
"date": "2014-09-01",
"trendingValue": "1114"
}];
});
angular.module('chart').directive('crD3Bars', [
function() {
return {
restrict: 'E',
scope: {
data: '='
},
link: function(scope, element) {
function getDate(d) {
var dt = new Date(d.date);
dt.setHours(0);
dt.setMinutes(0);
dt.setSeconds(0);
dt.setMilliseconds(0);
return dt;
}
function showData(obj, d) {
var coord = d3.mouse(obj);
var infobox = d3.select(".infobox");
// now we just position the infobox roughly where our mouse is
infobox.style("left", (coord[0] + 100) + "px");
infobox.style("top", (coord[1] - 175) + "px");
$(".infobox").html(d);
$(".infobox").show();
}
function hideData() {
$(".infobox").hide();
}
var drawChart = function(data) {
// define dimensions of graph
var m = [10, 20, 10, 50]; // margins
var w = 250 - m[1] - m[3]; // width
var h = 100 - m[0] - m[2]; // height
data.sort(function(a, b) {
var d1 = getDate(a);
var d2 = getDate(b);
if (d1 == d2) return 0;
if (d1 > d2) return 1;
return -1;
});
var minDate = getDate(data[0]),
maxDate = getDate(data[data.length - 1]);
var x = d3.time.scale().domain([minDate, maxDate]).range([0, w]);
var y = d3.scale.linear().domain([0, d3.max(data, function(d) {
return d.trendingValue;
})]).range([h, 0]);
var line = d3.svg.line()
.x(function(d, i) {
return x(getDate(d)); //x(i);
})
.y(function(d) {
return y(d.trendingValue);
});
function xx(e) {
return x(getDate(e));
}
function yy(e) {
return y(e.trendingValue);
}
var graph = d3.select(element[0]).append("svg:svg")
.attr("width", w + m[1] + m[3])
.attr("height", h + m[0] + m[2])
.append("svg:g")
.attr("transform", "translate(" + m[3] + "," + m[0] + ")");
var xAxis = d3.svg.axis().scale(x).ticks(d3.time.months, 1).tickSize(-h).tickSubdivide(true);
var yAxisLeft = d3.svg.axis().scale(y).ticks(10).orient("left"); //.tickFormat(formalLabel);
graph
.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("fill", "steelblue")
.attr("r", 5)
.attr("cx", xx)
.attr("cy", yy)
.on("mouseover", function(d) {
showData(this, d.trendingValue);
})
.on("mouseout", function() {
hideData();
});
graph.append("svg:path").attr("d", line(data));
$("#graphDiv3").append("<div class='infobox' style='display:none;'>Test</div>");
};
drawChart(scope.data);
}
};
}
]);
<!DOCTYPE html>
<html ng-app="chart">
<head>
<script data-require="angular.js#1.4.8" data-semver="1.4.8" src="https://code.angularjs.org/1.4.8/angular.js"></script>
<script data-require="d3#3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
<script data-require="jquery#2.1.4" data-semver="2.1.4" src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script src="script.js"></script>
</head>
<body>
<div id="graphDiv3" ng-controller="chartCtrl">
<cr-d3-bars data="myData"></cr-d3-bars>
</div>
</body>
</html>

Resources