Proper method to link information using angular.extend within a completed promise

My goal is to enhance the clarity of my Angular code by transitioning from using this.vm to angular.extend to better understand private and public variables/methods when utilizing the controller as syntax. However, I am facing an issue with data binding from a resolved promise.

// public data to view

var resolvedData;
var otherVar;

angular.extend(this, {
  myVar: resolvedData,
  mySecondVar: otherVar
})

myFactoty.action().then(function(data){
  resolvedData = data;
})

When implementing the code in the above manner, I am unable to achieve data binding in my view. To address this, I attempted the following approach:

// public data to view

var resolvedData;
var otherVar;

angular.extend(this, {
  myVar: resolvedData,
  mySecondVar: otherVar
})

myFactoty.action().then(function(data){
  angular.extend(this, {
    myVar: data
  })
})

However, this resulted in an error message: "Cannot read property '$$hashKey' of undefined."

How can I establish proper data binding in a manner that aligns with best practices?

Thank you.

Answer №1

It seems like there may be a lack of clarity in the code you're working with. The issue stems from `this` not behaving as expected within the promise callback function.

// Make sure to store a reference to `this`
var vm = this;

myFactory.performAction().then(function(data){
  // Within this function, `this` is not equivalent to `vm`
  angular.extend(this, { // This approach will not work as intended
    myVariable: data
  });
});

To properly extend the controller, make sure to use the stored reference within any enclosed functions.

myFactory.performAction().then(function(data){
  angular.extend(vm, {
    myVariable: 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

Utilizing Jquery to locate the precise HTML element or content that is positioned at a specific pixel location on the

I am trying to track down the exact HTML element or content occupying a specific pixel position on a web page. I am currently using jQuery and the scrollTop() method like this: $(window).scroll(function (event) { var scroll = $(window).scrollTop(); ...

The ideal version of firebase for showing messages in the foreground

Looking to instantly display notifications as soon as they are received? I recently watched a video on Angular 8 + Firebase where version 7.6.0 was discussed. While the notification is displayed in the foreground for me, I find that I need to click on some ...

A function similar to setCell for modifying form fields in JqGrid

After searching through numerous answers from @Oleg, I couldn't find the solution I was looking for. I am dealing with a grid where I can edit inline in certain fields. Specifically, I am working with autocomplete functionality and when I select an it ...

What is the best way to connect the state of a variable from one class to another in React?

How can I utilize the variable "restaurants" in Editar2.js? ---App.js--- const { restaurantes } = this.state; ---Editar2.js--- const ChooseRestaurant = (props) => { const options = props.restaurants.map((option) => { return(<opt ...

Showing a JSON array with varying nested lengths in an HTML5 format

I have a JSON string containing nested arrays with elements of unequal lengths. I am looking to display this data on a page using either Javascript or Angular.js. { [ 'id':1, 'value':'tes1' 'nextLevel':[&ap ...

Initial React render fails to retrieve API data

I've encountered an issue during development where the page loads before the API data is sent. I attempted to use asynchronous functions, but it didn't resolve the problem as expected. I suspect that my approach may be incorrect. Here's a sn ...

What is the method to create a resizable table column border rather than resizing the bottom corner border?

At the moment, we are able to resize the table border when we drag the corner. However, my goal is to enable resizing on the right side of the full border. https://i.sstatic.net/yFI24.png Below is the CSS code for resizing: th{ resize: horizontal; ove ...

What causes the discrepancy between the values returned by the jQuery getter css() method and JavaScript when accessing the style variable

After recently beginning to use jquery, I decided to switch due to initialization issues when loading external styles with javascript. Here is a rule defined in an external style sheet: #siteLogoDiv { position:absolute; left:0px; top:0px; width:100%; heig ...

"Stay current with real-time updates in seconds using React technology

Check out this code snippet: const currentTime = new Date().getTime(); const targetTime = new Date('November 15, 2020').getTime(); const difference = currentTime - targetTime; let seconds = Math.floor(difference / 1000) % 60; setInterval(functio ...

Download function in Express.JS failing to retrieve file

I have been working on a Node.JS server using Express to generate and download PDFs based on user input. Previously, I used the <form action=""> method to call my API, but switched to Axios due to Netlify not supporting NuxtAPI. The program ...

unable to retrieve the .id attribute from a resource

When attempting to access $scope.mySlot.id, it appears to be undefined. $scope.removeMe = function() { var shouldRemove = confirm('Are you sure you want to remove yourself from this field trip?'); ...

Issue with cookies modification in Next.js 14 server actions

I'm currently facing a challenge while working on a Next.js 14 project where I am trying to make changes to cookies. Despite carefully following the Next.js documentation regarding server actions and cookie manipulation, I keep running into an error w ...

Breaking Long Strings into Multiple Lines Using React Material UI Typography

Currently, I am working with ReactJS and incorporating MaterialUI components library into my project. However, I have encountered a problem with the Typography component. When I input a long text, it overflows its container without breaking onto a new lin ...

How can we stop the brief display of a hidden div from occurring?

I have two divs on my webpage - one to display if JavaScript is disabled, and another if JavaScript is enabled. The issue I am facing is that even when JavaScript is not disabled, the div containing the message stating that JavaScript is disabled briefly ...

The optimal method to simulate a $http promise in this particular situation

I am trying to work with a factory function that directly returns an http promise. It is several layers deep, but I am only interested in mocking the success and error parts of it. This is what the code looks like: user.create() .success(function(res ...

Looking for a way to retrieve JSON data from an HTML page using JavaScript? Look no further

There is a page that sends me JSON data. You can make the request using the GET method: or using the POST method: argument --> unique_id=56d7fa82eddce6.56824464 I am attempting to retrieve this information within my mobile application created with I ...

Modify the appearance of a specific side of a CircleGeometry shape over a set period of time

As a novice in the world of Three.js, I recently completed a crash course and now have a basic understanding of its capabilities. I managed to create a rotating disc on my website with my own image/texture, but I would like to change the texture/image on ...

Printing the result of an SQL query in Node.js without using braces

As a beginner in node.js with only a basic understanding of javascript, I apologize if I make any mistakes. I attempted to display the results retrieved by an SQL query in node.js using: <p>Users are " + util.inspect(results) + ".</p>" an ...

Struggling to get collapsible feature functioning on website

I'm trying to create a collapsible DIV, and I found a solution on Stack Overflow. However, I'm having trouble getting it to work on my website. I created a fiddle with the full code, and it works there. But when I implement it on my site, the con ...

Guide to adding a new entry to a database table using ajax

At the moment, I have a webpage displaying a grid of employee photos. Each employee has both an IN and OUT photo, named firstname_here.jpg and firstname_away.jpg respectively. By clicking on a photo, it toggles between the two images. Our setup consists ...