且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

AngularJS - 如何在自定义指令中更改 ngModel 的值?

更新时间:2022-11-19 09:27:35

有不同的方法:

  1. $setViewValue() 更新视图和模型.大多数情况下就足够了.
  2. 如果您想断开视图与模型的连接(例如,模型是一个数字,而视图是一个带有千位分隔符的字符串),那么您可以直接访问 $viewValue$modelValue代码>
  3. 如果您还想覆盖 ng-model 的内容(例如,指令更改小数位数,同时更新模型),请注入 ngModel: '=' 在作用域上设置 scope.ngModel
  1. $setViewValue() updates the view and the model. Most cases it is enough.
  2. If you want to disconnect view from the model (e.g. model is a number but view is a string with thousands separators) then you could access directly to $viewValue and $modelValue
  3. If you also want to overwrite the content of ng-model (e.g. the directive changes the number of decimals, updating also the model), inject ngModel: '=' on the scope and set 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
        }
 ...

链接: