AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

前端 未结 28 3152
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 22:31

I\'m finding that I need to update my page to my scope manually more and more since building an application in angular.

The only way I know of to do this is to call

28条回答
  •  庸人自扰
    2020-11-21 23:23

    I had the same problem with third parties scripts like CodeMirror for example and Krpano, and even using safeApply methods mentioned here haven't solved the error for me.

    But what do has solved it is using $timeout service (don't forget to inject it first).

    Thus, something like:

    $timeout(function() {
      // run my code safely here
    })
    

    and if inside your code you are using

    this

    perhaps because it's inside a factory directive's controller or just need some kind of binding, then you would do something like:

    .factory('myClass', [
      '$timeout',
      function($timeout) {
    
        var myClass = function() {};
    
        myClass.prototype.surprise = function() {
          // Do something suprising! :D
        };
    
        myClass.prototype.beAmazing = function() {
          // Here 'this' referes to the current instance of myClass
    
          $timeout(angular.bind(this, function() {
              // Run my code safely here and this is not undefined but
              // the same as outside of this anonymous function
              this.surprise();
           }));
        }
    
        return new myClass();
    
      }]
    )
    

提交回复
热议问题