Code: http://plnkr.co/edit/xPZM5E7tjYqlt5NIabIu?p=preview line-no:17
In this code if I use ctrl.$modelValue = nVal; instead of $parse(attrs.ngModel).assign(scope, nVal); then it does not work. Can you please point-out the reason?
angModule.directive('moChangeProxy', function ($parse) {
return {
require:'^ngModel',
restrict:'A',
link:function (scope, elm, attrs, ctrl) {
var proxyExp = attrs.moChangeProxy;
scope.$watch(proxyExp, function (nVal) {
if (nVal != ctrl.$modelValue) {
//ctrl.$modelValue = nVal; // This does not work
$parse(attrs.ngModel).assign(scope, nVal); // This works well
}
});
elm.bind('blur', function () {
var proxyVal = scope.$eval(proxyExp);
if(ctrl.$modelValue != proxyVal) {
scope.$apply(function(){
$parse(proxyExp).assign(scope, ctrl.$modelValue);
});
}
});
}
};
});
I guess that by "does not work" you mean that when the change occurs, it does not run stuff like all the $formatters and update the $viewValue?
If so, this is because ngModelController watches the "model expression" for changes rather than watching its own $modelValue.
See these lines: https://github.com/angular/angular.js/blob/master/src/ng/directive/input.js#L1046-L1065
If you update the model then the watch is triggered and all the machinery gets put into action. If you $modelValue, the ngModelController is not aware of the change.