编译指令会导致错误:$ apply已在进行中

时间:2013-07-22 16:22:38

标签: jquery angularjs angularjs-directive

这看起来很简单。

在Angular JS中,当用户单击页面上的链接时,我正在尝试编译指令。为此,我有一个ng-click处理程序。

<a ng-switch-when="grade" id="{{ item.gb_class_id }}" ng-click="showHWClick(item.gb_class_id, item.period_id, item.student_id)" href="">{{ item.grade }}</a>

...在我的控制器中,我定义了ng-click功能:

$scope.showHWClick = function(classId) {

        $('#' + classId).parent().parent('.grade-row').after($compile('<tr><td class="homework-row" colspan="9"><progress-report /></td></tr>')($scope));

    }

这是我的指示:

.directive('progressReport', function() {
    return {
        restrict: 'E',
        templateUrl: 'Content/app/dashboard/progressreport.html'
    }
});

所以,我只是在用户点击链接时编译模板。问题是,这会返回以下错误消息:

  

Error: $apply already in progress at Error (<anonymous>) at beginPhase (http://localhost:81/content/lib/angular/angular.js:8334:15) at Object.Scope.$apply (http://localhost:81/content/lib/angular/angular.js:8136:11) at Object.$delegate.__proto__.$apply (http://localhost:81/#/:855:30) at done (http://localhost:81/content/lib/angular/angular.js:9170:20) at completeRequest (http://localhost:81/content/lib/angular/angular.js:9333:7) at XMLHttpRequest.xhr.onreadystatechange (http://localhost:81/content/lib/angular/angular.js:9303:11) at http://localhost:81/content/lib/angular/angular.js:9312:11 at sendReq (http://localhost:81/content/lib/angular/angular.js:9146:9) at $http (http://localhost:81/content/lib/angular/angular.js:8937:17)

     

Error: Failed to load template: Content/app/dashboard/progressreport.html at Error (<anonymous>) at http://localhost:81/content/lib/angular/angular.js:4549:17 at http://localhost:81/content/lib/angular/angular.js:8957:11 at wrappedErrback (http://localhost:81/content/lib/angular/angular.js:6855:57) at http://localhost:81/content/lib/angular/angular.js:6931:53 at Object.Scope.$eval (http://localhost:81/content/lib/angular/angular.js:8057:28) at Object.Scope.$digest (http://localhost:81/content/lib/angular/angular.js:7922:25) at Object.$delegate.__proto__.$digest (http://localhost:81/#/:844:31) at Object.Scope.$apply (http://localhost:81/content/lib/angular/angular.js:8143:24) at Object.$delegate.__proto__.$apply (http://localhost:81/#/:855:30)

无法加载模板错误很奇怪,因为我已经检查了模板位置的四倍,这是正确的。但我认为错误是第一条错误消息的结果。

有谁知道什么是错的?提前谢谢。

编辑:Here's the Plunker

编辑2:我正在使用Angular 1.0.7。

2 个答案:

答案 0 :(得分:3)

您不应该在指令之外进行DOM操作。您的showHWClick函数可能修改范围内的某些属性或对象,而不是修改DOM。然后,您的模板将绑定到该属性,并像任何其他角度模板一样进行更新。

http://docs.angularjs.org/tutorial/已涵盖此内容。

如果我不得不猜测你想要完成什么,你可能想看一下1.1.5中引入的ngIf指令来有条件地添加一块DOM(不仅仅是显示/隐藏它。)

答案 1 :(得分:1)

我已经修改了点击事件,您可以尝试下面的代码:

$scope.showHWClick = function(classId) {
        $timeout(function(){
            if (!$scope.$$phase) {
                $('#' + classId).parent().parent('.grade-row').after($compile('<tr><td class="homework-row" colspan="9"><progress-report /></td></tr>')($scope));
            }
        }, 500, false);

    }