Angularjs 在指令中更新模型时,表单 $error 不会更新,除非模型被清除

Angularjs form $error is not getting updated when the model is updated inside a directive unless the model be cleared

我无法弄清楚以下示例中发生了什么。我只是想在我自己的指令中创建我自己的 required 验证,我有一个数组,我想让它成为必需的(这是我想做的事情的简化,但足以说明这一点)

提琴手:http://jsfiddle.net/gsubiran/p3zxkqwe/3/

angular.module('myApp', [])

.directive('myDirective', function($timeout) {
    return {
      restrict: 'EA',
      require: 'ngModel',
      controller: 'myDirectiveController',
      controllerAs: 'D_MD',
      link: function(scope, element, attrs, ngModel) {
        ngModel.$validators.required = function(modelValue) {
          var result = false;
          if (modelValue && modelValue.length > 0)
            result = true;

          return result;
        };
      },
      bindToController: {
        ngModel: '='
      },
      template: '(<span>ArrayLength:{{D_MD.ngModel.length}}</span>)<br /><input type=button value="add (inside directive)" ng-click=D_MD.AddElem() /><br /><input value="clear (inside directive)" type=button ng-click=D_MD.Clear() />'
    };   })   .controller('myDirectiveController', [function() {
    var CTX = this;
    //debugger;
    //CTX.ngModel = "pipo";
    CTX.clearModel = function() {
      CTX.ngModel = [];
    };
    CTX.AddElem = function() {
      CTX.ngModel.push({
        Name: 'obj100',
        Value: 100
      });
    };
    CTX.Clear = function() {
      CTX.ngModel = [];
    };   }])   .controller('MainCtrl', function($scope) {
    var CTX = this;
    CTX.patito = 'donde esta el patito';
    CTX.arrayElements = [];
    CTX.setElements = function() {
      CTX.arrayElements = [{
        Name: 'obj0',
        Value: 0
      }, {
        Name: 'obj1',
        Value: 1
      }, {
        Name: 'obj2',
        Value: 2
      }];
    };
    CTX.clearElements = function() {
      CTX.arrayElements = [];
    };   })

当我点击 add (outside directive) 按钮时,所需的工作正常, 但是当我点击 add (inside directive) 按钮时,我仍然在表单中收到所需的错误(表单是在指令外部定义的)。

但更让我困惑的是:

当我在点击 add (outside directive) 按钮后点击 clear (inside directive) 按钮使所需的错误消失时,在这种情况下,表单正在更新并显示验证错误。

为什么当我向数组添加新元素时 $validations.required 没有在指令内部触发,但是当我清除它时是?

有什么想法吗?

******* 更新 *******

它似乎与 array.push 有关,如果我更改 array.push 并分配新数组,其中包含所需元素,它工作正常。 仍然是为什么会发生的问题。

作为解决方法,我在指令中以这种方式更改了 AddElem 函数:

CTX.AddElem = function() {
     CTX.ngModel = CTX.ngModel.concat({
        Name: 'obj100',
        Value: 100
      });
    };

你这里用的ngModel是一个JS对象。 Angular 在其 $modelValue$viewValue 中引用了该对象(因为 angular 基本上是 $viewValue = $modelValue)。 $modelValuengModel 的实际值,如果您更改它,将在 运行 $validators 之后更改 $viewValue

要了解您的 ngModel 是否已更改,angular 将 ngModel.$viewValuengModel.$modelValue 进行比较。在这里,您正在对 $viewValue 执行 push(),同时更新 $modelValue,因为它们只是彼此的引用。因此,当比较它们时,它们具有相同的值!这就是为什么 angular 没有 运行 你的 $validator

The docs explain it :

Since ng-model does not do a deep watch, $render() is only invoked if the values of $modelValue and $viewValue are actually different from their previous values. If $modelValue or $viewValue are objects (rather than a string or number) then $render() will not be invoked if you only change a property on the objects.

如果我过度简化了 angular 代码,此片段对此进行了解释:

var myArray = [];

var ngModel = {
  $viewValue: myArray,
  $modelValue: myArray,
  $validate: function () { console.log('validators updated'); }, // log when validators are updated
}

function $apply() { // the function that is called on the scope
  if (ngModel.$viewValue !== ngModel.$modelValue) {
    ngModel.$viewValue = ngModel.$modelValue;
    ngModel.$validate(); // this will trigger your validator
  } else {
    console.log('value not changed'); // the new value is no different than before, do not call $validate
  }
}

// your push is like doing :
ngModel.$viewValue.push(12); 
$apply(); // will output 'value not changed', because we changed the view value as well as the model value

// whereas your should do:
var newArray = [];
// create a copy of the array (you can use angular.copy)
for (var i = 0; i < myArray.length; i++) {
  newArray.push(myArray[i]);
}
ngModel.$viewValue.push(12);
ngModel.$viewValue = newArray; // here we clearly update the $viewValue without changing the model value
$apply(); // will output 'validators updated'

当然不是强制你做一个数组拷贝。相反,您可以强制更新您的 ngModel。这是通过调用 ngModel.$validate();

完成的

一种方法是在您的 scope 中添加一个 forceUpdate() 函数,并在您执行 push();

之后从控制器中调用它

示例:http://jsfiddle.net/L7Lxkq1f/