tamtakoe
tamtakoe

Reputation: 237

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

I try update model from directive and have some trouble when $apply or $digest already in progress. And I have some questions:

  1. Why scope[attrs.ngModel] is exist, but ngModel.$modelValue isn't exist in $apply phase?
  2. Why view can be not always updated in $digest phase (especially in difficult situations)?
  3. Is $digest phase local $digest() or $root.$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

Upvotes: 4

Views: 1242

Answers (1)

lgersman
lgersman

Reputation: 2286

  1. Thats because angular does'nt know how to map the model to your DIV element. angular has builtin model implementations for almost any INPUT (except INPUT type file), SELECT and TEXTAREA element. In your case (a DIV with a applied ng-model) there is no matching model adapter known to angular. what property/attribute of the DIV element should take angular to be in sync with your model ?? thats why ou have no $modelValue applied. what you have to do is to provide a custom model adapter to angular OR you need to use a INPUT, SELECT or TEXTAREA element.

  2. because in $digest phase angular assumes all changes are done.

  3. there is no local or global $digest phase. phases are always associated to your ng-app.

Upvotes: 2

Related Questions