angular.js - 使用angularjs,如何在document ready中修改model,并且使得与model绑定的dom被更新?
怪我咯
怪我咯 2017-05-15 16:50:52
0
2
566

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

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(2)
洪涛

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

仅有的幸福

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template