AngularJs directive change ngModel with delay & model's value don't match

179 Views Asked by At

Ng-change is acting weird in a directive. It seems to have a delay in the digest cycle resulting in the wrong (previous) ngModel value in controller immediately after the change.

ngModel : '='

https://codepen.io/anon/pen/moEgdG

What's going on and how to fix?

1

There are 1 best solutions below

3
georgeawg On

With the ng-model directive on a component, I recommend using one-way (<) for the input and $setViewValue on the output:

app.directive('newTag', function(){
  return {
    template: `
       <input ng-model="test" ng-change="change(test)"> <br/>
       {{test}}
    `,
    restrict: 'E',
    require: "ngModel",  
    scope: {
        ngModel : '<',
    },
    link: function (scope, elem, attrs, ngModel) {
      scope.change = function(val) {
        ngModel.$setViewValue(val);
      };
    },
  };
})

Usage:

<new-tag ng-model="tagValue" ng-change("newTagUpdate(tagValue)")>
</new-tag>

For more information, see