Getting a $rootScope:inprog error, but it requires scope.$apply to work

Blaise picture Blaise · Feb 17, 2015 · Viewed 7.8k times · Source

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.

Answer

Scottie picture Scottie · Feb 17, 2015

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());
        })
    }

  });