javascript - 为什么 NgModelController.$modelValue != $parse(attrs.ngModel)(scope)?

标签 javascript angularjs

代码: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/

相关文章:

JavaScript OR (||) 变量赋值解释

javascript - 更改位置时出现 Safari 渲染问题 :fixed to position:relative

javascript - 通过变量访问属性时出现语法错误?

angularjs - 在输入文本框的占位符中渲染特殊字符

angularjs - 在可重用的 Angular 指令中隔离范围

c# - 如何使用 Angularjs 从字典列表的成员中检索数据?

javascript - 如何从 div id 小到最大数字开始 .each?

php - 匹配多列所在位置... PHP PDO

javascript - 发送 Angular POST 请求

javascript - fabricjs 路径的边界框偏移量