angularJS-- data has not been updated but the view layer update problems and solutions

Handling from: https://www.cnblogs.com/yky-iris/p/9251230.html?utm_source=debugrun&utm_medium=referral

 

View does not update problems and reasons:  Under js native or third-party frameworks, modify model, it is possible to not trigger a view update, such as setTimeout, jquery plugins. Because they are out of context Angularjs, Angularjs not listen to the changed data.

Solution: using Apply $ () to manually update the view, as follows.

html:

<p>{{name}}</p>

js:

$ scope.name = "John Doe" ; 
the setTimeout ( function () { 
    $ scope.name = 'John Doe' ;
     // $ $ scope Apply (). 
}, 500)

 

  A. $ The Apply (), Digest concept  

 

  Role $ apply () function:  allows expression from the outside Angular within the framework of the implementation of Angular context.

  $ apply () function works: the equivalent of a flip-flop, its role is to trigger digest cycle, thereby updating the view.

  What digest that? : Digest is the core Angularjs is that it realized the magic of data binding. Any trigger event will trigger digest cycle, such as ng event, click, change, actually triggered the digest cycle.

 

 

  II. Better use digest   

  In Angularjs, in addition to $ apply can trigger digest cycle, there are other ways, also can trigger this cycle. And $ apply tend to be the worst choice. The following recommended some better choices.

 

(1). $digest

$ Scope. $ Digest () speed apply to be fast, because it only updates the current value of the scope and sub-scope, regardless of scope for the parent than the $. And $ apply also assess the parent scope, which is a significant drain on performance.

(2). $timeout

With $ timeout to replace your setTimeout, $ timeout as Angularjs of service comes, of course, when it is more fit Angularjs environment. It will trigger digest recessive cycle, and it will delay the execution, a digest will be the next moment after the cycle is completed on the trigger digest cycle, so there is no mentioned above   

$digest already in progress

 

We setTime code into the $ timeout

$timeout(function(){
  $scope.name = '李四';
},500)

This can work normally, look, do not apply the nasty!

(3). $evalAsync

When this method is the most recommended should. If you happen to have a digest of the current cycle in execution, then it will cause the operating cycle of the digest, digest into the current cycle to execute. The $ timeout to wait until the current digest cycle executed, perform another cycle before they can digest. So evalAsync perform faster and better performance. We can call it like that to $ timeout, that is,

$scope.$evalAsync(
    function( $scope ) {
        console.log( "$evalAsync" );
    }
);

Guess you like

Origin www.cnblogs.com/linjiangxian/p/12221296.html