jqueryangularjsvisualize

Angular scope not updating in after JQuery call


I am using jasper reports in my angular based website. Jasper report's visualize.js includes jQuery. When i load a report i update a value in my scope

$scope.reportLoaded = true

but is not being updated in the page

{{reportLoaded}} //false

I guess that probably this is a conflict between angular and jQuery. The only way to solve this is to use the $scope.$$apply() which i have read that we shouldn't use it. How can i solve this issue without using the apply? Is it safe to use it, if there isn't other way to solve the issue?


Solution

  • Any updation in the scope which is not done by angular is not noticeable to angular. so you have to use $scope.$apply(); when you update any value in current $scope.

    Angular is a two way data binding mechanism, so when you change the model updates the view and vice-versa. Internally angular runs a $digest cycle which does all the checks in the current $scope. As long as you are doing updation in the $scope variables within angular things go normally but outside of it like, if you change values with native javascript or other libraries like jQuery then $digest cycle has to be run, this is where $scope.$apply() comes handy.


    $scope.$digest() is also very useful and it is quite faster than $scope.$apply() because it $scope.$digest() runs in current scope but $scope.$apply() runs on $rootscope and internally fires $rootscope.$digest().

    $scope.$digest() to use this first you need to setup a scope watcher and what it actually does is, it constantly watches the scope changes and by any means wheter it is from angular or from other sources like yours in this case is perfect example to setup a scope watcher if you want to use with $scope.$digest().

    $scope.$watch('reportLoaded', function(newValue, oldValue, scope) {
       scope.reportLoaded = newValue !== oldValue ? newValue : oldValue;
    });