I am facing an issue in my Angular application where the data retrieved from an API is not being passed properly from a controller function to a directive function. Despite using .then() to ensure sequential execution, I still receive 'undefined' data in the directive function. The controller function works fine with the retrieved data, but it fails to pass it to the directive function.
Here is an overview of my code:
Controller
angular.module('myControllerModule', ['getData'])
.controller('myViewController', function($scope, getDataFactory){
// Mapping the directive function to controller
$scope.setDirectiveFn = function(directiveFn){
$scope.directiveFn = directiveFn;
};
// Function for calling the factory and directive function
$scope.search = function(){
$scope.RetreivedData = getDataFactory.getTheData()
.then(function successCallback(response){
$scope.data = response.data; // Data is not passed
}).then($scope.directiveFn())
};
});
Factory
angular.module('getData',[])
.factory('getDataFactory', function($http){
return{
getTheData: function() {
return $http({
url: 'url/to/API/endpoint',
method: 'GET'
})
},
}
});
Directive
angular.module('myChartModule')
.directive('chart', function (){
return{
restrict: 'E',
scope: {
data: '=',
setFn: '&',
},
controller: 'myViewControllerr',
templateurl: '/path/to/my/template/file.html',
link: function link(scope, element, attr){
scope.drawChart = function(){
var chartData = scope.data; //undefined
console.log(chartData);
};
// mapping the directive function to controller
scope.setFn({theDirFn: scope.drawPSA});
}
}
});
HTML
<chart data='data' set-fn="setDirectiveFn(theDirFn)"></chart>
I am struggling to identify the root cause of this issue and find a solution. It's unclear why the data is not being passed correctly between the controller and directive functions.