代码:http://plnkr.co/edit/xPZM5E7tjYqlt5NIabIu?p=preview 第 17 行
在这段代码中,如果我使用 ctrl.$modelValue = nVal;
而不是 $parse(attrs.ngModel).assign(scope, nVal);
那么它会不行。能否请您指出原因?
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);
});
}
});
}
};
});
最佳答案
我猜“不起作用”是指当更改发生时,它不会运行所有 $formatters 之类的东西并更新 $viewValue?
如果是这样,这是因为 ngModelController 监视“模型表达式”的变化而不是监视它自己的 $modelValue。
查看这些行:https://github.com/angular/angular.js/blob/master/src/ng/directive/input.js#L1046-L1065
如果您更新模型,那么 watch 就会被触发,所有的机器都会投入运行。如果您 $modelValue,则 ngModelController 不知道更改。
关于javascript - 为什么 NgModelController.$modelValue != $parse(attrs.ngModel)(scope)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14522107/