0

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">)

Web Develop Wolf
  • 5,996
  • 12
  • 52
  • 101
  • Could you provide the html? My suspicion is that it's not properly bound, in the html `{{}}` refers to items on `$scope` and `$scope !== this` – Patrick Barr Jul 03 '17 at 15:26
  • 2
    use `$http` service instead of `$.ajax` and recommend to do read up on [Thinking in AngularJS” if I have a jQuery background?](https://stackoverflow.com/q/14994391/2435473) – Pankaj Parkar Jul 03 '17 at 15:27
  • 1
    Just added the HTML - forgot to add it to the question – Web Develop Wolf Jul 03 '17 at 15:27
  • Possible duplicate of ['this' vs $scope in AngularJS controllers](https://stackoverflow.com/questions/11605917/this-vs-scope-in-angularjs-controllers) – Patrick Barr Jul 03 '17 at 15:28

1 Answers1

1

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.

Himanshu Upadhyay
  • 6,558
  • 1
  • 20
  • 33