AngularJS – 如何改变自定义指令ngModel的值?

让我们看看我的指示:

angular.module('main').directive('datepicker', [ function() { return { require: '?ngModel', link: function(scope, element, attributes, ngModel) { ngModel.$modelValue = 'abc'; // this does not work // how do I change the value of the model? 

那么,如何改变ng模型的价值呢?

有不同的做法:

  1. $setViewValue()更新视图和模型。 大多数情况下就够了。
  2. 如果你想从模型断开视图(例如模型是一个数字,但视图是一个string与千位分隔符),那么你可以直接访问$viewValue$modelValue
  3. 如果你还想覆盖ng-model的内容(例如指令改变小数位数,也更新模型),在范围中注入ngModel: '=' ,并设置scope.ngModel

例如

  return { restrict: 'A', require: 'ngModel', scope: { ngModel: '=' }, link: function (scope, element, attrs, ngModelCtrl) { function updateView(value) { ngModelCtrl.$viewValue = value; ngModelCtrl.$render(); } function updateModel(value) { ngModelCtrl.$modelValue = value; scope.ngModel = value; // overwrites ngModel value } ... 

链接:

  • 第一个选项在这里讨论
  • NgModelController官方文档

要处理复杂的绑定expression式,您应该使用$ parse服务和assign方法。

要了解更多信息,请观看ng-conf上的video – 使用ng-model指令可以做的很酷: https : //www.youtube.com/watch?v = jVzymluqmg4

 app.directive('datepicker', ['$parse', function($parse) { return { require: '?ngModel', link: function(scope, element, attributes, controller) { // $parse works out how to get the value. // This returns a function that returns the result of your ng-model expression. var modelGetter = $parse(attributes['ngModel']); console.log(modelGetter(scope)); // This returns a function that lets us set the value of the ng-model binding expression: var modelSetter = modelGetter.assign; // This is how you can use it to set the value 'bar' on the given scope. modelSetter(scope, 'bar'); console.log(modelGetter(scope)); } }; } ]); 

你尝试的是实际上工作: 看到这个Plunker

您不要在input中“看到”它,因为以这种方式更改模型不会调用controller.$render()来设置新的controller.$viewValue

但是,你为什么不简单地改变$scope值(除非你不知道,但它会很奇怪):

 angular.module('main').directive('datepicker', [function() { return { require: '?ngModel', link: function(scope, element, attributes, controller) { var model = attributes['ngModel']; scope[model] = 'bar'; } }; }]); 

并在你的html:

 <input ng-model="yourVariable" datepicker> 

编辑:(dynamic解决scheme)

 angular.module('main').directive('datepicker', [function() { return { require: '?ngModel', link: function(scope, element, attributes, controller) { // get the value of the `ng-model` attribute var model = attributes['ngModel']; // update the scope if model is defined if (model) { scope[model] = 'bar'; } } }; }]); 

这适用于我的网站上的DatePicker

 link: function(scope, elem, attrs, ngModel) { scope.$apply(function(){ ngModel.$viewValue = value; } } 

这是我遇到的最好的解释。 这帮助了我很大的时间,并汇集了其他一些答案的细节。

提示:小心阅读整篇文章,而不是撇号,否则你可能会错过一些关键点!

https://www.nadeau.tv/using-ngmodelcontroller-with-custom-directives/