Web Develop Wolf
Web Develop Wolf

Reputation: 6326

Angular variable not updating on front-end

I have an application in angularjs, it runs with no errors but there's just one particular variable passed to the front-end that is not updating. I've declared, populated and initiated it in the controller, but it still sits at zero:

(function () {
 "use strict";
 angular.module("HtJobPortal").controller("JobController", JobController);

    JobController.$inject = ["$scope", "$rootScope"];

    function JobController($scope, $rootScope){      
        var job = this;
        job.global = $rootScope;
        job.pendingCount = 0;
        job.penStr = "http://...";

        job.getPending = function () {
            $.ajax({
                method: "GET",
                crossDomain: true,
                url: job.penStr,
                dataType: "json",
                success: function (data) {
                    job.fillPending(data);
                    job.pendingCount = data.Data.length;
                }
            });
        }

        // Initialise pending and set roles
        job.init = function () {
            job.getPending();
        }
    };
    job.init();
    }
})();

The rest of the application works as expected and the job.fillPending(data); works with no errors and creates the table it's supposed to. I've put a break point on job.pendingCount = data.Data.length; and that tells me that the length is 1, but this is never reflected in the pending count, which remains at zero.

The HTML output is:

<h3>Showing {{job.pendingCount}} Pending Bookings</h3>

This does change if the initial creation variable at the start of the controller is changed. (EDIT: The reason 'job' proceeds the count, is because the controller has an alias when attached to the template <main class="main" ng-controller="JobController as job">)

Upvotes: 0

Views: 1590

Answers (1)

Himanshu Upadhyay
Himanshu Upadhyay

Reputation: 6565

Event handlers are called "outside" Angular, so even if your $scope properties will be changed, the view part will not be updated because Angular doesn't know about these changes.

Call $scope.$apply() after your event handler. This will cause a digest cycle to run, and Angular will notice the changes you made to the $scope and update the view.

Upvotes: 1

Related Questions