AngularJS: Dealing with scope loss in a directive following a promise

I am currently facing a major issue within my Angular application.

There is a Factory in my code that makes an HTTP request to retrieve spoolers and returns a promise.

Spooler.prototype.load = function () {
    var self = this;
    var deferred = $q.defer();
    $http.post('/spooler/' + this.id + '/load')
        .success(function(data) {
            self.statistics = data.statistics;
            deferred.resolve(self);
        })
        .error(function(err, code) {
            deferred.reject(err);
        $log.error(err, code);
    });
    return deferred.promise;
};

The problem arises in my controller when utilizing the "then()" keyword. The values within this then() statement are passed to a directive as shown below:

$scope.load = function(){
        spooler.load().then(
            function(dataSpooler){
                $scope.spooler = dataSpooler;
                $scope.custom = 4; 
            },
            function() {
                $scope.dataFail = 'error error' ;
            }
        );
    }

While logging the variable custom in the view shows '4', I encounter issues when using this variable in my directive:

<highchart-pie items="custom"></highchart-pie>

Below is the code for the directive:

 .directive('highchartPie', function () {
    return {
        restrict: 'E',
        replace: true,
        scope: {
           items : '='
        },
        template: '<div style="width:100%;margin: 0 auto;">not working</div>',
        link: function (scope, element, attrs) { 
                console.log(scope); // i can see the item value 4
                console.log(scope.items); !!! undefined !!!
                // Link function is actually way bigger and renders the element to the template (useless to be shown)
        }
    }

In conclusion, assigning $scope.custom = 4; inside the then() function seems to cause delays in the directive receiving the values. However, if I declare $scope.custom = 4; at the beginning of the controller before the then() method, everything functions smoothly.

Any insights or suggestions would be greatly appreciated! Thank you in advance! :)

Answer №1

one approach is,

$scope.load = function(){
        return spooler.load().then(
            function(data){
                $scope.spooler = data;
                $scope.custom = 4; // demonstrating a random variable inside the promise
            }
            function() {
                $scope.dataFail = 'error error' ;
            }
        );
    }

although not the optimal method,

$scope.load = spooler.load;

and then,

$scope.load().then(
                function(data){
                    $scope.spooler = data;
                    $scope.custom = 4; // demonstrating a random variable inside the promise
                }
                function() {
                    $scope.dataFail = 'error error' ;
                }
            );

Answer №2

It's important to note that in this scenario, the console.log statement executes before the promise is actually resolved, resulting in undefined items being printed. As suggested by @Razvan Balosin, it's crucial to $watch over the items array to notify Angular of any changes, allowing you to properly handle the data once it becomes available.

Answer №3

My recommendation is as follows:

link: function link(scope, element, attrs) {
 scope.$watch('film',function(item){
   // if there is any data in film, render chart
   if(item) {
    console.log("Scope: " , scope);
    console.log("Film:", scope.film); // works now
   }
  })
}

Check out the updated plunker

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

Tips for extracting chosen values from ui-selects within ng-repeat

I have a scenario where I'm dynamically adding ui-selects using ng-repeat. However, I am struggling to figure out how to retrieve the selected value from each ui-select separately in the controller. My goal is to grab the selected item's value in ...

What is preventing me from accessing my session array in this.state.props from my mapStateToProps in React-Native Redux?

I am currently facing an issue with my Redux store setup. I am attempting to store an array of Session objects, where each Session object contains an array of Hand objects. However, when trying to access my store using `mapStateToProps`, none of the option ...

Is there a way to confirm if the target has been successfully removed from the element using jQuery?

$(".dropdown-toggle").click(function(event) { var target = $(event.target); if (target.is(this)) { $(this).find(".caret").toggleClass("customcaret"); } }); <div class="dropdown-toggle"> <div class="caret"></div> </div> ...

Modifying color in CSS for an SVG that is dynamically animated using JSON

I recently obtained an animated hamburger menu icon for free from this particular website. The animation triggers on click and reverses on the second click, functioning smoothly. Now, I am seeking guidance on changing its color using CSS. // JSON var ...

Is it possible to utilize router.push within Redux thunk? Is this considered a beneficial approach?

I have this anchor element: <a className="btn btn-sm btn-circle" href={`https://www.facebook.com/sharer/sharer.php?u=${ process.env.NEXT_PUBLIC_ENVIRONMENT == "prod" ? "https://tikex.com" : "https:/ ...

Storing the model on the server with the help of Backbone and NodeJS

As a beginner in Backbone and AJAX, as well as being new to Node.js which my server is built on, I am working on saving a model using the Save method in Backbone for a webchat project for university. Right now, my goal is to send the username and password ...

uncertainty about the process of deleting an HTML dropdown item element

I'm in the process of building a dynamic menu that changes based on whether a user is logged in on a webpage. Check out the HTML code I've used (Bootstrap 4): <div class="dropdown" id="account_info"> <butto ...

What methods are available to verify the local installation of an NPM package that I have released?

After successfully releasing a new package on NPM, I encountered an issue. While the package performs flawlessly on my computer, errors pop up when my coworker tries to install it using 'npm install'. What is the optimal method for installing an ...

Basic HTTP request to retrieve user's geographical location

I've been working on a project that involves getting the user's location and sending it to the server for API calls. I'm able to retrieve the current location of the user, but for some reason, it's not posting to the server as expected. ...

Problem with declaring Javascript objects

Exploring the world of OOP for the first time, encountering a small challenge: const panel = { image : imgs[24], proportion : this.image.height / this.image.width, height : this.image.height - (scale), width : height / proportion, ...

Once the if condition is implemented, the functionality of the toggle button ceases to operate

Take a look at this demo link: http://jsbin.com/labuxuziraya/1/edit I encountered an issue where the button stops working after adding an if condition. I suspect there are some minor bugs in the code, but my level of experience is not enough to pinpoint t ...

Using ID attributes to compare JavaScript Objects and generate a distinct list within Angular/JS

I am working with the github API to retrieve an array of objects containing commit data. My goal is to extract a unique list of commitors and format it as shown below to create a graph: {"id":temp,"label":temp,"type": "number","p": {} } Here is the code ...

It appears that there is a slight hiccup in the code when JavaScript is implementing the line skip functionality for the condition

Currently, I am working on a textbook exercise that involves the classic 99 Bottles of Beer on the wall JavaScript program. However, this assignment does not come with any examples or answers for reference. Despite searching online for assistance, the code ...

Adding javascript code to each page in an asp.net application

I am in the process of implementing GTM on a website with over 400 pages where the GTM script needs to be placed. Is there a way to automatically inject the GTM script on every page right after the body tag? The website utilizes a mix of technologies, in ...

Executing npm and ng commands via an Ant script on a Windows machine leads to the error message "The specified file could not be found."

When attempting to execute the following Ant script, which runs the "npm" command: <target name ="test"> <exec executable="npm" failonerror="true"> <arg value="install" /> </exec> </target> An error occurs, i ...

What is the best way to create an array from every individual line in a textarea using AngularJS?

I am trying to create a textarea that is linked to a JS array, where each line in the text area corresponds to an entry in the array. I have been experimenting with ngList and its optional parameter for specifying the delimiter. While I can make it work w ...

Change the term to its corresponding translation

I have developed an Ionic Multilingual App that includes a select feature. Within this select, choosing a specific option disables certain page elements. However, I am facing an issue where one of the elements needs to change its text based on the selected ...

A step-by-step guide to identifying the clicked bar on a Chart.js graph

When using Chart JS to create a line bar chart, I am looking to specifically identify which bar was clicked on the chart and determine the index of that bar. This will allow me to display specific details for each clicked bar on a table. For example, click ...

Is there a way to create a Vue component that can process dynamic formulas similar to those used in

I am looking to create a component that has the ability to accept different formulas for computing the last column. The component should use these formulas in Vuex getters to store the total state values passed to it. Here are the specifications for the c ...

How to defer the rendering of the router-outlet in Angular 2

I am currently working on an Angular 2 application that consists of various components relying on data fetched from the server using the http-service. This data includes user information and roles. Most of my route components encounter errors within their ...