4

Is there a way of applying scope in the snippet below without it throwing an error? (and without hacks and workaround like try/catch, $timeout or hard-coding BONJOUR)

Without SCOPE.$apply(), the alert shows {{HELLO}} instead of BONJOUR.

var app = angular.module('APP', [])
  .controller('CTRL', function($scope, $compile) {

    $scope.showBonjour = function() {
      var SCOPE, CONTENT;

      SCOPE = $scope.$root.$new();
      SCOPE.HELLO = 'BONJOUR';

      CONTENT = $compile('<div>{{HELLO}}</div>')(SCOPE);

      SCOPE.$apply(); // This generates the $rootScope:inprog error, but I cannot omit it…

      window.alert(CONTENT.html());
    }

  });
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js"></script>

<html ng-controller="CTRL" ng-app="APP">
    <button ng-click="showBonjour()">Show BONJOUR</button>
</html>
Blaise
  • 13,139
  • 9
  • 69
  • 97

2 Answers2

10

Using $timeout isn't a hack. It's used quite often in Angular to wait until the current digest cycle is completed, then do something.

Here's a working Plunker:

http://plnkr.co/edit/XAA1wo0Ebgmk0NqB85BC?p=preview

  var app = angular.module('APP', [])
    .controller('CTRL', function($scope, $compile, $timeout) {

      $scope.showBonjour = function() {
        var SCOPE, CONTENT;

        SCOPE = $scope.$root.$new();
        SCOPE.HELLO = 'BONJOUR';

        CONTENT = $compile('<div>{{HELLO}}</div>')(SCOPE);

        $timeout(function() {
          window.alert(CONTENT.html());
        })
    }

  });
Scottie
  • 11,050
  • 19
  • 68
  • 109
  • Totally agree with the use of $timout not being a hack. – mccainz Feb 17 '15 at 16:13
  • Respectfully disagree on $timeout not being a hack. Yes, it's useful and easy to implement on the fly, but understanding how to use use $apply with respect to function execution within and outside of the Angular context is a best practice. Here is a good resource I've found on understand various $scope use cases: https://medium.com/@TuiZ/digest-already-in-progress-c0f97a6becfc#.q6y5wfalt – Wes King Dec 28 '15 at 17:29
  • Okay... so how would you fix this users issue without using $timeout? I'm very curious if there is a better way to do it. Post an answer with your $apply code. – Scottie Dec 28 '15 at 21:24
  • Would love to see an answer here, as I've just had to use it. – Simon Mar 15 '16 at 23:50
0

you can try this

make a new function like this:

$scope.applyif=function()
{                
            if(!$scope.$$phase) {
                $scope.$apply();
            }else
            {
                setTimeout(function(){$scope.applyif();},10);
            }
}

after call $scope.applyif() in place of $scope.$apply()

ro0xandr
  • 105
  • 7