有没有办法在下面的代码段中应用范围而不会引发错误?(并且没有 hack 和解决方法,例如try/catch
,$timeout
或硬编码 BONJOUR)
如果没有SCOPE.$apply()
,则显示警报{{HELLO}}
而不是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>