How to Angular update a view after a $ digest loop?

It:

1) Launch the DOM (starting from ng-app), and if it sees a DOM node with a directive, update the DOM node with the appropriate model value.

or

2) When running through a list $$watchers, if it detects a change, it refers to the DOM node that it needs to update, so it just does it (therefore, instead of working through the entire DOM using this approach, it will save and use the link to node c $$watchers).

+4
source share
1 answer

This is more of a second approach.

Angular . , Angular, :

<div ng-app>
<div ng-controller>
<button ng-click>

<!-- input is actually a directive -->
<input ng-model="foo" />

DOM, , $scope. , , - .

, .

, , . $digest , , , ( ).

, . , DOM.

, . , , - .

, DOM - .

(function(){

  function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}
  
  function updateValue(){
    return {
      restrict:'A',
      link: function(scope, elem, attrs){
        elem.on('click', function(){
          //You would never actually do this, but
          // it a demo
          scope[attrs.updateValue] = "rgb(" + 
            getRandomInt(0, 255) + "," +
            getRandomInt(0, 255) + "," +
            getRandomInt(0, 255) + ")";
          
          //kick off a digest loop manually
          // this is similar to what a lot of angular
          // directives do.
          scope.$digest();
        });
      }
    };
  }
  
  function sillyDomChangeOn(){
    return {
      restrict:'A',
      link: function(scope, elem, attrs){
        scope.$watch(attrs.sillyDomChangeOn, function(newVal, oldVal){
          elem.css('color', newVal);
        });
      }
    };
  }
  
  angular.module('my-app', [])
    .directive('updateValue', updateValue)
    .directive('sillyDomChangeOn', sillyDomChangeOn);

}());
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">

<div ng-app="my-app" class="container">
  <button type="button" class="btn btn-primary" update-value="randomVal">Update Value</button>
  <h3>Value: <code>{{randomVal}}</code></h3>
  <div class="well" silly-dom-change-on="randomVal">
  <h3>This is just a random DIV</h3>
    <div>
</div>
Hide result
+3

Source: https://habr.com/ru/post/1617366/


All Articles