AngularJs model not being updated

I am currently in the process of transitioning from Knockout to Angular. However, I have encountered some challenges that I haven't been able to overcome yet.

Within the login function of my website, I make an ajax call to retrieve user information which is then set in the controller.

This is how it looks:

    $scope.login = function () {

        var data = {
            userName: $('#txtLoginName').val(),
            password: $('#txtLoginPassword').val(),
        };

        console.info(data);

        postJSON("/StrengthTracker/User/Login", data, function (result) {

            if (result.result == "ok") {
                $('#loginDialog').modal('hide');

       //setting controller variables <------------
                $scope.isLoggedIn = true;
                $scope.userId = result.userId;
                $scope.userName = result.userName;
                $scope.publicId = result.publicId;
                $scope.gender = result.gender;
                $scope.unitName = result.unit;

                console.info(result);

                notify("Welcome " + $scope.userName);
            }
            if (result.result == "fail") {
                notifyFail("Login failed");
            }
        });
    }

Although the correct data is returned and the notify(..) call displays "Welcome Roger" for instance, it seems like Angular doesn't recognize that the variables have been updated.

Only when I trigger the login function again does Angular acknowledge the changes and realize that the user is logged in.

Any thoughts or suggestions?

Answer №1

The issue here stems from AngularJS not recognizing your callback function, as it is not being tracked. Following Yoshi's advice, employing $scope.$apply resolves this by ensuring AngularJS acknowledges it.

It is worth noting that AngularJS includes native functionalities for handling AJAX requests using $http and $resource (specifically for REST services). Utilizing these objects has its perks - you no longer need to manually implement $apply, plus your code can easily undergo testing with the innate support for unit tests.

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

Customize ACF Google Map - Adjusting the Look?

I have successfully set up and running a Wordpress site, where I utilized the ACF plugin to create a Google Map field. Everything is working fine, but I wish to modify the default style of the map. I specifically need a lighter grayscale theme for my websi ...

Can TypeScript support the use of typed streams?

When working with TypeScript and using the typings from @types/node, streams default to using the any type. While this may suffice in most cases, it is not the most optimal approach as data emitted through the data event typically has a consistent type, es ...

The Laravel route is guiding me to a different destination

Currently, I am facing an issue while trying to develop a CRUD application using Laravel and vue.js. Every time I launch the application, it redirects me to the dashboard but the CRUD functionalities are not visible. Below are the codes from Routes/web.a ...

Mastering the art of modifying click events with jQuery

Currently, I am delving into the world of JavaScript and JQuery, specifically exploring a reference for the click event from jquery.js. In my endeavors, I have attempted to override the click event, but to no avail. Despite my efforts to make the new even ...

Enhancing fancybox with dynamic scrollbars as the window size changes

I'm currently working on a popup form that I'm displaying with Fancybox 2 by using the code below: $(link).fancybox({ type: 'iFrame', autoSize: false, autoScale: false, width: '1280px', height: '1024p ...

jQuery puzzle: a form within a form within a form

I am facing a bit of a dilemma with a partially working solution. The scenario is this - I am using a basic .load() function attached to a <select> element to fetch another form populated through PHP/MySQL. What I intend to achieve is for this newly ...

AngularJS - Discover the art of transmitting complex data with $http.get() requests

My JSON array is structured as follows: var myData = { foo : { biz : 'baz', fig : 'tree' } } If I type this into the address bar: http://www.mysite.com/index?foo[biz]=baz&foo[fig]=tree It works perfectly ...

Using AngularJS to make asynchronous calls to hprose.httpclient

I am currently facing an issue with my Hprose server and user authentication. My goal is to create a logonService that will return a UserInfo object after the user has successfully logged in. The problem lies in the asynchronous nature of hprose.HttpClie ...

When executing my code to delete a file and remove it from the database, an error message pops up in the console

I've been working on implementing a delete image feature on my website. Although my code successfully deletes the file from the images folder and removes the corresponding record from the database, I encounter an error in the console that prevents me ...

applying a timeout for the .on(load) event

My goal is to dynamically load images using .on('load') in the script below: .on('load', function() { if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) { alert('broken i ...

I'm constantly running into a logic issue that is causing my array output to be filled with zeros

I seem to have encountered a tricky logic error in my code where the output is not as expected due to values not being returned correctly. I'm seeking guidance on how to troubleshoot this issue. Before delving into that, let me provide some context ab ...

Using AJAX to dynamically inject a JavaScript function into the webpage

When I load a portion of a page using AJAX calls, sometimes the loaded content may contain script functions attached to controls with different events. The issue arises when these events are triggered, resulting in an error message saying "object not found ...

Use jQuery's `append` function only if it is

What is the best way to append only if a telephone number exists and skip if a telephone number does not exist? for (var i in data.businesses) { if (data.businesses[i].telephone) { $('body').append( "<p>" + data.businesses[i]. ...

dynamically assessed the level within the map function

After finding inspiration from Rafael Freitas, I was able to craft this updated function for MongoDB: const updated = await db.Mother.update({ "cards.advanced.unit": card.unit }, [ { $set: { "cards.adva ...

Discovering the Weekend using JavaScript - A Step-by-Step Guide

Currently, I am developing a basic JavaScript function to determine if today is considered a working day based on a list of working sequences. JavaScript function IsWeekOff(ToDay, WorkingSequence) { var Sun_Thu = {0:"Sun",1:"Mon",2:"Tue",3:"Wed", ...

Transferring a precise sum to PayPal

I've recently ventured into the world of creating a price calculation sheet with javascript, and while I'm still learning, I've managed to put together something that works well (thanks to a variable called "finalTotalPrice"). However, my n ...

Kendo dropdown list won't trigger the change() event

I am using a Kendo DropDownList to load data from JSON. However, the onchange event of the dropdownlist is not firing. <input class="ddEmailInitiation" /> <script>$(".ddEmailInitiation").kendoDropDownList ({ dataTextField: "Type", dataSour ...

Should React.cloneElement be used to pass new children or copy props.children?

I am having trouble understanding the third parameter "children" of React.cloneElement and how it relates to this.props.children. After reading a helpful guide on higher order components, I implemented the following code: render() { const elementsTre ...

Can you tell me how to achieve the functionality of the ".get" statement in JavaScript that is present in python-firebase?

After writing Python code that retrieves the entire JSON database, I attempted to achieve the same functionality in JavaScript without success. Despite its apparent straightforwardness, I have yet to discover a viable solution. var firebase = require(&apo ...

Updating an object within an array of objects can be achieved by utilizing the setState method in React

I'm currently working with React, where my state is structured as an array of objects. I'm looking for a way to specifically update only one element in the state.data array, such as the object with id 1. I'm curious about: how to properly ...