4

有没有办法在下面的代码段中应用范围而不会引发错误?(并且没有 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>

4

2 回答 2

10

使用 $timeout 并不是一个技巧。在 Angular 中经常使用它来等待当前的摘要周期完成,然后做一些事情。

这是一个工作的 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());
        })
    }

  });
于 2015-02-17T15:57:38.617 回答
0

你可以试试这个

做一个这样的新功能

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

在调用 $scope.applyif() 代替 $scope.$apply()

于 2016-02-24T12:30:52.480 回答