I have successfully created a custom Angular directive that utilizes D3.js to create a visualization. In my HTML, I reference this directive as follows:
<gm-link-analysis data="linkAnalysis.connections"></gm-link-analysis>
The relevant part of the directive code is shown below:
angular.module('gameApp')
.directive('gmLinkAnalysis', gmLinkAnalysis);
gmLinkAnalysis.$inject = ['$location', 'd3'];
function gmLinkAnalysis($location, d3) {
var directive = {
restrict: 'E',
templateUrl: '/app/gmDataVis/gmLinkAnalysis/gmLinkAnalysis.directive.html',
controller: 'LinkAnalysisController',
controllerAs: 'linkAnalysis',
scope: {
data: '='
},
link: function(scope) {
scope.$watch('data', function(json) {
console.log(json);
if (json) {
root = json;
root.fixed = true;
root.x = width / 2;
root.y = height / 2;
return scope.render(root);
}
});
...
}
};
return directive;
};
...and here is my controller:
angular.module('gameApp')
.controller('LinkAnalysisController', LinkAnalysisController);
LinkAnalysisController.$inject = ['$routeParams', 'dataVisService'];
function LinkAnalysisController($routeParams, dataVisService) {
var vm = this;
var userId = $routeParams.userId;
var getConnections = function() {
dataVisService.getConnections({
userId: userId
}).$promise.then(function(connections) {
vm.connections = connections;
console.log(vm.connections);
});
};
var init = function() {
getConnections();
};
init();
}
I am facing an issue where it seems like my directive loads before my controller fetches the data. Initially, I see undefined
in the logs within the directive, followed by the actual data in the controller logs. While I understand that the directive may load before the asynchronous API call completes in the controller, I am unsure why the $watch
does not capture this data once it is available. How can I ensure that the data gets passed to my directive correctly?