angularJS報錯$apply already in progress的原因和解決方案

來源:互聯網
上載者:User

標籤:ase   sdn   ext   root   timeout   text   疑問   angularjs   bsp   

如果我們使用了AngularJS中的$scope.$apply()或者$scope.$digest(),我們很可能會遇到類似下面的錯誤,雖然這個錯誤沒有太大影響,但是在日誌中看起來還是很不爽的,日誌中記錄的異常或者錯誤,就應該是需要關注和解決的問題,否則就沒有必要出現在日誌中了。

原因是:angularjs架構本身已經在做髒資料檢測了,我們沒有必要再手動調用$apply或者$digest。這裡自然而然出現了一個疑問:什麼時候需要我們手動調用$apply或者$digest,什麼時候不需要呢?先列出以下兩種情況:

情況1:controller中如果有非同步作業,比如ajax回調,timeout延時等。可以這麼理解:由於非同步(延遲)的存在,當開始執行回呼函數的時候,angularJS自身controller中的髒值檢測已經結束,無法檢測到回呼函數導致資料的變化。

 1 //html 2 <div>{{text}}</div> 3  4 //js 5 var myModule = angular.module(‘myModule‘, []);     6 myModule.controller("ctrl_1",function($scope){   7      $scope.text = "place";   8                9       setTimeout(function(){  10            $scope.text = "value setted after time out";  11            $scope.$apply();//必需手動進行髒值檢測,否則資料無法重新整理到介面  12        },1000);  13           14 });  

用$timeout service來代替setTimeout(),不需要手動調用$apply(), $timeout service會自動調用$apply();

情況2:在jQuery代碼中修改$scope中的資料。這種情況是在angular架構之外操作$scope中的資料,angular不能檢測到資料變化是正常的。

//js<script>            var myModule = angular.module(‘myModule‘, []);    myModule.controller("ctrl_1",function($scope){              $scope.text = "place";  });             $(function(){       angular.bootstrap($("#div1")[0], ["myModule"]);           $("#btn").click(function(){               var $scope = $("#btn").scope();               $scope.text = "value setted in jquery";               $scope.$apply();         });           })  </script> //html<div id="div1" ng-controller="ctrl_1">          <div>{{text}}</div>          <input id="btn" type="button" value="jquery-event"></input>           </div>   

如何判斷是否需要手動調用$apply()呢?

$$phase 是 angluar 內部使用的狀態標誌位,用於標識當前是否處於 digest 狀態。

$scope.safeApply = function(fn){   var phase = this.$root.$$phase;   if (phase == ‘$apply‘ || phase == ‘$digest‘) {       if (fn && ( typeof (fn) === ‘function‘)) {          fn();       }   } else {       this.$apply(fn);   }}

angularJS報錯$apply already in progress的原因和解決方案

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.