The Angular data model fails to update when the URL is modified

SOLUTION: var deferred2 = $q.defer(); It is important to place this inside the method _getSpecificPerson(), as visiting other Person promises in already resolved. This ensures that a new deferred object is created each time.

Imagine having a list of persons and visiting a details page with a unique URL like: #/PersonDetails/0c4274ed-ae76-4648-bba4-434a3040b9c5. However, upon returning to view details of another person, the same page is shown even after sending a new request for the other person's data. Angular seems to ignore new data if it was previously populated.

Relevant code snippet:

 personModule.controller("PersonDetailsController", function ($scope, $http, dataService, $routeParams) {
    var id = $routeParams.PersonId;
    var myPromise = dataService.getSpecificPerson(id);
    myPromise.then(function (result) {
        var returnedPerson = result;
        if (returnedPerson.AllXml) {
            $scope.OnePerson = JSON.parse(returnedPerson.AllXml);
        }
    });

});

   personModule.factory('dataService', function ($http,$q) {
    var deferred = $q.defer();
    var deferred2 = $q.defer();
    var _getPersons= function() {
        $http.post(ROOT + 'Home/GetPersons').
            then(function(data, status, headers, config) {
                deferred.resolve(data.data);
            },function () {
                deferred.reject();
            });
        return deferred.promise;
    }

    var _getSpecificPerson = function (id) {
        var dataString = {
            id:id
        }
        $http.post(ROOT + 'Home/GetPerson', dataString).
            then(function (data, status, headers, config) {
                deferred2.resolve(data.data);
            }, function () {
                deferred2.reject();
            });
        return deferred2.promise;
    }
    return {
        getPersons: _getPersons,
        getSpecificPerson:_getSpecificPerson
    }

}); I attempted to assign my scope within $scope.$apply() but encountered the error: $digest already in progress. Note that the factory function returns correct data from the service, but when using myPromise.then(function(result){ in the controller, the result is cached. However, when logging data.data inside the factory method, _getSpecificPerson returns up-to-date data.

Answer №1

If everything is stored in JSON format, you should have no trouble writing

$scope.Person = returnedPerson.AllData;

You can also streamline your service

var _getPersonDetails = function (id) {
    var requestData = { id:id };
    return $http.post(ROOT + 'Home/GetDetails', requestData);
}

Since the post method returns a promise. To make it work in your controller, you need to make this adjustment:

var returnedDetails = response.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

Using asynchronous JavaScript (AJAX) to request a file to be processed on the client-side

I have a query that I need help with: My goal is to retrieve a file from the server after it has undergone input-dependent processing through an AJAX request (such as using jQuery). However, I don't want to directly offer this file for download in th ...

Choosing HTML Elements for Audio Playback in HTML5: A Guide to Selecting Elements Without Using Div IDs

When creating an HTML5 player, I am transitioning "from using divs with id's" to "simple HTML elements". Former Scenario (functional) <audio src="track1.mp3" id="audio"></audio> <controls> <play id="play" style="display:none ...

As I embark on building my web application using next.js, I begin by importing firebase from the "firebase" package. Unfortunately, a particular error unexpectedly surfaces in the terminal

I am currently developing a next.js web application and I have decided to utilize firebase for both database management and authentication. However, when attempting to import firebase in a specific file, I encountered the following error: Error - ./firebas ...

Grabbing <object> HTML using jQuery

One example on my webpage is the presence of the following <object>: <object id="obj1" data="URL"></object> Could you please suggest a method to access this html object using jQuery? ...

Guide to retrieving RabbitMQ queue messages in Vue.js application

I am currently working on a project using Spring Boot to publish messages to RabbitMQ and then push them to a queue. I also have a Vue.js frontend application that needs to consume these messages from the RabbitMQ queue. Despite searching online, I haven ...

Creating links within a single image in HTML?

Is there a way to hyperlink different parts of a single image to various webpages using JavaScript coordinates or any other method? ...

What is causing the error message "generator function required" to appear on my screen?

I recently installed the npm module called "koa-cache-control" and inserted the following code lines into my index.js file. const cacheControl = require('koa-cache-control'); After that... app.use(cacheControl({ noCache: true })); Upon sta ...

Fetching jQuery library via JavaScript

Having trouble loading the JQuery library from a JavaScript file and using it in a function. JS1.js $(document).ready(function () { //var id = 728; (function () { var jq = document.createElement('script'); jq.type = 'te ...

Utilizing a promise instead of making a jQuery ajax request

A scenario I am facing involves a function that is set to execute jquery.ajax and return it as a promise for future processing. However, in certain cases, the function possesses enough information to proceed synchronously without triggering the ajax call. ...

Receiving and transmitting messages repeatedly in Discord.JS

Currently, I am developing a simple bot. Interestingly, the bot seems to be responding multiple times to a single command. Here is the code snippet: const Discord = require('discord.js'); var bot = new Discord.Client(); const PREFIX = "+"; var ...

Updating a MongoDB subarray with $set now includes adding a new entry rather than just updating existing ones

When trying to update an object in a sub-array, instead of replacing and updating the data, it adds a new entry. Here is the code from controller.js: const updateSubCategory = asyncHandler(async (req, res) => { const { dataArray } = req.body ...

Locating function definitions in etags using Emacs

I find syntax check in js2-mode to be quite effective. However, there are times when I wish to name a function "delete" or "new" even though it may not be the best practice. Js2-mode often flags this as an error. Is there a way to use built-in keywords as ...

Creating a hash from a string in Javascript

I'm struggling with the process of converting a string into a nested hash in JavaScript. Here is the string I want to convert: "{'btc_usd': {'price': 376.2, 'volume': 42812.69, 'change': -0.5},'btc_cn ...

Streamline the entire testing process of Google.Com by using Protractor to automate end-to-end testing

I need help with making Protractor navigate to google.com and search for a term. After successfully loading the non-angular page of Google, I am struggling to figure out how to make Protractor press "enter" or click the search button. Any suggestions? Ad ...

Tracking Clicks on Folders in jQuery File Tree

I am attempting to integrate a jQuery file tree into my website using the example provided below: Check out this jQuery file tree example While I can successfully trigger an event when a file is clicked, as demonstrated in the example, I am struggling to ...

The link in the drop down select is not functioning in IE8/9. When trying to open the drop down select link, an

Could use some help with IE8 and 9 compatibility, can't seem to find a solution. This code works smoothly on Chrome, FF, and Safari. There are two dropdown menus, each with two links. Every dropdown menu has its own "Buy Now" button. Upon selecting ...

Struggling with developing a chrome extension

I have successfully developed a Chrome extension that, when clicked, says hello world. However, I am facing an issue with creating a simple button that triggers an alert when pressed. Could it be due to the inclusion of JavaScript in an HTML extension file ...

HTML: Base64 image not displaying properly due to incorrect height specification

I have a straightforward base64 image that I am having trouble with. The issue is that only the upper half of the image is displaying. If I try to adjust the height using the "style" attribute in the img tag: style="height: 300px;" it shows correctly. Ho ...

React doesn't have file upload configured to update the state

I am working on integrating a file upload button that sends data to an API. To ensure only the button triggers the upload dialog and not the input field, I have set it up this way. Issue: The File is not being saved to state, preventing me from using a ...

AngularJS NG-Grid displaying incorrect value for select cell

I'm working on creating a table with a column that needs to be selected based on a value received from the server. The server sends me 4 as the value, but the first option is always selected instead. $scope.lotteryOptions = { data: 'myDa ...