Update model from $ apply or $ digest cycle directive in AngularJS

I am trying to update a model from a directive and have some problems when $ apply or $ digest is already running. And I have a few questions:

  • Why scope[attrs.ngModel] exist, but ngModel.$modelValue not in the $ apply phase?
  • Why might the view not always be updated in the $ digest phase (especially in difficult situations)?
  • Whether $ digest is a local $ digest () or $ root phase. $ digest () (from $ apply ()) in my example?
 require: '?ngModel', link: function(scope, element, attrs, ngModel) { element.bind('myEvent', function(e) { //Update model from directive in phase: $apply | $digest scope[attrs.ngModel].value = scope.$$phase; //Model: '$apply' | '$digest' //or ngModel.$modelValue.value = scope.$$phase; //Model: 'none' | '$digest' //or ngModel.$modelValue.value = scope.$$phase; //Model: '' | '$digest' ngModel.$setViewValue(ngModel.$modelValue); }); } 

Live demo: http://plnkr.co/edit/gVY6GJejEKCLdTIXNAzK?p=preview

+4
source share
1 answer
  • This is because angular does not know how to map the model to your DIV element. angular has built-in model implementations for almost any INPUT (except a file of type INPUT), a SELECT element, and TEXTAREA. In your case (DIV using ng-model) there is no corresponding model adapter known by angular. What property / attribute of the DIV element should angular accept to synchronize with your model? That is why you do not have $ modelValue. you need to provide a custom model adapter for angular OR you need to use an INPUT, SELECT or TEXTAREA element.

  • because in the $ digest angular phase it is assumed that all changes are made.

  • The local or global phase of $ digest is missing. phases are always associated with your ng application.

+2
source

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


All Articles