Transferring information from a method within a controller to a method within a directive using Angular

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.

Answer №1

After some troubleshooting, I finally managed to resolve the issue. The problem was with the promise chain implementation. I made a tweak by encapsulating the directive function call within the controller's search function using an anonymous function. As a result, the data is now successfully flowing through.

$scope.search = function(){
    $scope.RetreivedData = getDataFactory.getTheData()
        .then(function successCallback(response){
            $scope.data = response.data;
         })
         .then(function(data){
            $scope.directiveFn($scope.data)
         })
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript and DOM element removal: Even after the element is removed visually, it still remains in the traversal

Our goal is to enable users to drag and drop items from a source list on the left to a destination list on the right, where they can add or remove items. The changes made to the list on the right are saved automatically. However, we are encountering an iss ...

Using HTTP POST to subscribe and implementing a try-catch block

When using Angular2's http.post, I encountered an issue where the headers were not sent to the CORS server. To address this, I attempted to create a loop that would retry the request until it succeeds. However, this resulted in an endless loop. How ca ...

Javascript is not functioning properly when making an ajax call

Having a bit of trouble with JavaScript not working after an Ajax call. Everything functions normally until new data is fetched from the database or an Ajax call is made. The issue seems to be that the JavaScript doesn't load properly. Any help would ...

Is it possible for jcarousel to interact with a database as well?

Hey there, I've been searching everywhere but couldn't find any information on how to make jcarousel work with a database. That's why I'm reaching out here for some help. I have a page where I'm using jcarousel. css js Currently ...

transfer an image file to a php script using ajax

Having just started, my goal is to upload an image and send it to a server for insertion into a database. Initially, all I want to do is echo the file name that I will be sending. However, I am encountering issues with this process, as I keep receiving noi ...

The event SelectedIndexChanged is not triggering as expected on dropdown lists that are created dynamically

My Telerik RadComboBox triggers Javascript on change to fetch data from the database via AJAX and populate a second dropdown list. I need to fill text boxes based on the selection of the second dropdownlist. The code for the two dropdownlists is as follows ...

I'm receiving /generate_seeker/?complete_list=true, but what I actually need is /generate_seeker?complete_list=true

Check out this code snippet that utilizes axios in a React project. axios.get(`https://resolab-backend.herokuapp.com/core/create_seeker`,{ params:{ complete_list : true }, headers:{ 'Authorization': `Token ${cookies.get("token")}` } ...

How can I utilize the mapv tool created by Baidu in a Node project?

I need assistance converting the following code to a node environment. The code can be found at Here is the code snippet: var map = new BMap.Map(slice.selector, { enableMapClick: false }); // Create Map instance map.centerAndZoom( ...

Delayed callback on blur

I am developing an AutoComplete feature in React that displays a list of suggested completions as the user types into a text box. When a suggestion is clicked, it should trigger a callback function, and the dropdown should disappear when the text box loses ...

Tips for obtaining a variable step size in react-chartjs-2

I am currently utilizing Chart.js in typescript to create graphical charts. My objective is to dynamically adjust weight values while maintaining a specified minimum and maximum. Specifically, I aim to display 5 ticks on the Y-axis regardless of the incomi ...

An unconventional web address was created when utilizing window.location.hostname

I've encountered an issue while trying to concatenate a URL, resulting in unexpected output. Below you'll find the code I tested along with its results. As I am currently testing on a local server, the desired request URL is http://127.0.0.1:800 ...

Error: The function setEmail is not defined. (In 'setEmail(input)', 'setEmail' is not recognized) (Cannot utilize hooks with context API)

App.js const[getScreen, showScreen] = useState(false); const[getEmail, setEmail] = useState(""); <LoginScreen/> <LoginContexts.Provider value={{getEmail,setEmail,getScreen,showScreen}}> {showScreen?<Screen2/>:<LoginScre ...

Performing a Javascript ajax post of a canvas snapshot in "image/jpeg" format to an asp.net web form

Here is the JavaScript AJAX code snippet: var dataURL = canvas.toDataURL("image/jpeg"); var xhr = new XMLHttpRequest(); xhr.open("POST", "myPage.aspx", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechan ...

Vue-router vulnerability allowing for DOM-based open redirects

I am currently working on a Vue application that was created using Vue-cli. Vue version: 2.6.11 vue-router version: 3.2.0 Link for Reproduction https://github.com/keyhangholami/dom-based-open-redirect Instructions to replicate To reproduce the i ...

Leverage AngularJS to dynamically load CSS stylesheets using ng-repeat

I have organized my stylesheets into separate modules for each include, and I am trying to dynamically load them. However, I am facing some difficulties as when they are rendered, all I see is the following markup for each sheet that should be loaded: < ...

Errors caused by Typescript transpilation only manifest on the production server

During the process of updating my node version and dependencies on both machines, I came across an issue where building my app in production on one machine resulted in an error, while building it on my main machine did not. I found that the errors disappe ...

What is the best way to organize React components/modules in order to effectively separate the UI?

Currently, I have developed three key components for a dashboard UI project in React. These components include a sidebar, top navigation bar, and a content container. As someone who is new to React after working with Angular, I am now seeking advice on how ...

What is the reason behind the Typescript compiler not converting .ts files to .js files automatically?

Displayed below are the folders on the left showcasing my Typescript file in /src (blue) compiled into Javascript in /dist (purple) using tsc. https://i.stack.imgur.com/7XNkU.png In the source file on the left, there is a reference to a .ts module file t ...

Disable toolbar focus in TinyMCE

Is there a method to prevent the appearance of the white square known as "Focus to toolbar" in TinyMCE? Clarification: Upon pressing Alt+F10 in TinyMCE, a white square is outlined around a button on the toolbar. This allows navigation among toolbar butto ...

I am unable to implement code coverage for Cypress in Debian at the moment

Having trouble obtaining code coverage results using Cypress in my Virtual Machine (Debian Bullseye), but no issues when I run the same project on my Windows machine. On Linux, the code coverage shows up as: Click here to view Index.html inside lcov-repor ...