search

Home  >  Q&A  >  body text

angular.js - 使用angularjs,如何在document ready中修改model,并且使得与model绑定的dom被更新?

下面的例子中,model被修改了,但是界面没被更新
例子:
http://jsbin.com/relanafohu/4/edit

怪我咯怪我咯2743 days ago568

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-05-15 16:52:52

    https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$apply

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-15 16:52:52

    All model modifications in asynchronous operation callbacks that are not known to Angular need to use the apply method to explicitly notify angular to update the view. For details, see Angular's documentation on apply.

    In addition, if angular is in the process of updating (digest circle) and apply is called, the following error will appear:

    Error: $apply already in progress
    

    In order to avoid this error, you can first determine the current status and directly use the following encapsulated method:

    jssafeApply = function( scope, fn) {
        var phase = scope.$root.$$phase;
        if(phase == '$apply' || phase == '$digest') {
            if(fn && (typeof(fn) === 'function')) { fn();
            }
        } else {
            scope.$apply(fn);
        }
    }
    

    When you need to set the model, just:

    jssafeApply( $scope, function(){
        // 在这里写你修改model的代码
    });
    

    For more details about this error, check out this question on stackoverflow

    reply
    0
  • Cancelreply