2013-01-25 23 views
4

代码: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); 
        }); 
       } 
      }); 
     } 
    }; 
}); 

回答

7

我想通过“不工作”你的意思是,当变化发生时,它并不像所有的$格式化运行的东西,并更新$ viewValue?

如果是这样,这是因为ngModelController监视“模型表达式”的变化,而不是看自己的$ modelValue。

见这些行:https://github.com/angular/angular.js/blob/master/src/ng/directive/input.js#L1046-L1065

如果更新了模型,则手表被触发,所有的机器被付诸行动。如果您是$ modelValue,则ngModelController不知道更改。

+1

非常好!了解。 – SunnyShah

+0

我认为直接通过ctrl改变值。$ modelValueis滥用控制器的私有变量。 :) – SunnyShah

+0

我认为角应提供ngModelController.setModelValue()函数。 – SunnyShah

相关问题