I have decided to implement a chart library called Plotly in my project. To ensure reusability, I am creating a directive in AngularJS that will allow me to easily integrate the library in the future.
The directive will receive an object as input to create the graph. This object is fetched through an API call. Here's the code snippet:
CONTROLLER:
angular.module("app").controller("appDetailsController",
['$scope', '$http', function($scope, $http) {
$scope.graphData = {}
$http.get('/api/analytics/24').then(function(data) {
console.log('Loaded analytics data:', data);
$scope.graphData = data.data
})
}])
DIRECTIVE:
angular.module("app").directive("timelineGraph", function() {
return {
restrict: "E",
scope: {
data: "="
},
link: function(scope, element, attr) {
console.log("scope data:", scope, scope.data)
}
}
})
HTML:
<timeline-graph data="graphData"></timeline-graph>
When inspecting the "scope" inside the link function, I noticed that the data object is only populated after the API call. To handle this, I added a $watch function like this:
scope.$watch('data', function(data) {
if(data)
console.log('data changed:', data)
})
However, I am curious if there is a more efficient way to handle this scenario without relying heavily on the $watch function. Any suggestions would be appreciated.