I am attempting to create a graph on my webpage using the D3.js library for JavaScript. I am able to draw a line on an SVG using HTML, but when I try to draw a line using JavaScript, I encounter the error message:
ReferenceError: d3 is not defined
.
Even though I have included the D3.js file, I still face this issue.
Could you please advise me on how to overcome this problem?
You can view the Plunker here: https://plnkr.co/edit/pdDCfYmCQxX56sBfjfzW?p=preview
Below are the relevant files for your review.
Javascript:
myApp = angular.module('myApp', ['ui.router']);
myApp.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider.state('myState', {url: '/myState', params: {slug: {value: null, squash: true}}, templateUrl: 'my-state-page1.html', controller: 'MyStateCtrl'});
}
);
myApp.controller('MyStateCtrl', function($scope, $http) {
var self = this;
$scope.$watch(function() {return self.myDataFromAPI}, function(objVal) {
console.log('objVal = ', objVal);
x = objVal.origin.split('.');
console.log("X = ", x)
var svgContainer = d3.select("body").append("svg").attr("width", 1000).attr("height", 1000);
var line = svgContainer.append("line").attr("x1", x[0]).attr("y1", x[1]).attr("x2", x[2]).attr("y2", x[3]).attr("stroke-width", 2).attr("stroke", "black");
},
true
);
self.httpFailure = function(response) {
console.log('Failure');
self.myDataFromAPI = null;
}
self.httpSuccess = function(response) {
console.log('\n\n\nGot the data from the API!');
self.myDataFromAPI = response.data;
console.log('\n\n\self.myDataFromAPI =', self.myDataFromAPI);
}
$http.get(
'https://httpbin.org/get'
).then(self.httpSuccess, self.httpFailure);
}
);
myApp.directive('mypMyDirective', function() {
return {
restrict: 'E',
scope: {
myDataFromAPI: '='
},
controller: 'MyStateCtrl',
controllerAs: 'myStateCtrl',
bindToController: true,
templateUrl: 'myD3Diagram.html'
};
}
);
index.html:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.18/angular-ui-router.js"></script>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
HELLO!
<div ng-controller="MyStateCtrl as myStateCtrl">
<myp-my-directive mydatafromapi="myStateCtrl.myDataFromAPI"></myp-my-directive>
</div>
</body>
</html>
myD3Diagram.html:
<svg id="my_svg_widget" width="500" height="500>
<line x1="5" y1="5" x2="40" y2="40" stroke="gray" stroke-width="5" />
</svg>