0

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?

andrew
  • 9,313
  • 7
  • 30
  • 61
user3009752
  • 164
  • 2
  • 9
  • 24

2 Answers2

0

you MUST use $apply in these situations. this is what $apply is for. it is for saying

"hey angular, i did some changes without your knowledge. you should better run your dirty checking mechanism to see what has changed"

so, use $apply

bahadir
  • 709
  • 1
  • 11
  • 28
0

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;
});
Jai
  • 74,255
  • 12
  • 74
  • 103
  • I agree but everyone suggests not to use it. I also read it in the anti-patterns.So i should use a solution that is not suggested? – user3009752 Sep 17 '15 at 13:55
  • @user3009752 its true, you can use `$timeout` service to run the digest cycle then. – Jai Sep 17 '15 at 14:00
  • 1
    @Jai The anti-pattern here is using a jQuery ajax call. $timeout will do some things, and then call $scope.$apply(). – Deblaton Jean-Philippe Sep 17 '15 at 14:05
  • @deblatonjeanphilippe absolutely true! But I don't think other than `$scope.$apply()` is way out. – Jai Sep 17 '15 at 17:28