解释ngModel管道,解析器,格式化程序,viewChangeListeners和$ watchers的顺序

Jos*_*sep 9 angularjs angularjs-directive angularjs-scope

构建这个问题并不容易,所以我将尝试通过一个例子来解释我想知道的事情:

考虑一下这个简单的angularjs app:PLUNKER

angular.module('testApp', [])
.controller('mainCtrl', function($scope) {
  $scope.isChecked = false;
})
.directive("testDirective", function () {
    return {
        restrict: 'E',
        scope: {
            isChecked: '='
        },
        template: '<label><input type="checkbox" ng-model="isChecked" /> Is it Checked?</label>'+
                  '<p>In the <b>directive\'s</b> scope <b>{{isChecked?"it\'s checked":"it isn\'t checked"}}</b>.</p>'
    };
}); 
Run Code Online (Sandbox Code Playgroud)

有了这个html:

  <body ng-controller="mainCtrl">
    <test-directive is-checked="isChecked"></test-directive>
    <p>In the <b>controller's</b> scope <b>{{isChecked?"it\'s checked":"it isn\'t checked"}}</b>.</p>
  </body>
Run Code Online (Sandbox Code Playgroud)

该应用程序:

  • 有一个控制器叫做:"mainCtrl"我们定义了一个名为"isChecked"的范围变量
  • 它还有一个名为"testDirective"的指令,它带有一个隔离的范围和一个名为"isChecked"的绑定属性.
  • 在html中,我们在"mainCtrl"中实例化"testDirective",并将"mainCtrl"范围的"isChecked"属性与指令的隔离范围的"isChecked"属性绑定在一起.
  • 该指令呈现一个具有"isChecked"范围属性的复选框作为模型.
  • 当我们选中或取消选中复选框时,我们可以看到两个范围的两个属性同时更新.

到现在为止还挺好.

现在让我们做一点改变,像这样:PLUNKER

angular.module('testApp', [])
.controller('mainCtrl', function($scope) {
  $scope.isChecked = false;
  $scope.doingSomething = function(){alert("In the controller's scope is " + ($scope.isChecked?"checked!":"not checked"))};
})
.directive("testDirective", function () {
    return {
        restrict: 'E',
        scope: {
            isChecked: '=',
            doSomething: '&'
        },
        template: '<label><input type="checkbox" ng-change="doSomething()" ng-model="isChecked" /> Is it Checked?</label>'+
                  '<p>In the <b>directive\'s</b> scope <b>{{isChecked?"it\'s checked":"it isn\'t checked"}}</b>.</p>'
    };
}); 
Run Code Online (Sandbox Code Playgroud)

还有这个:

<!DOCTYPE html>
<html ng-app="testApp">
  <head>
    <script data-require="angular.js@1.3.0-beta.5" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>
  <body ng-controller="mainCtrl">
    <test-directive is-checked="isChecked" do-something="doingSomething()"></test-directive>
    <p>In the <b>controller's</b> scope <b>{{isChecked?"it\'s checked":"it isn\'t checked"}}</b>.</p>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

我们唯一做的就是:

  • 在控制器范围内定义一个函数,该函数window.alert指示是否选中或取消选中控制器范围的'isChecked'属性.(我正在window.alert故意这样做,因为我希望执行停止)
  • 将该函数绑定到指令中
  • 在"ng-change"中,该指令触发该功能的复选框.

现在,当我们选中或取消选中该复选框时,我们会收到警报,在该警报中,我们可以看到该指令的范围尚未更新.好吧,所以有人会认为ng-change在模型更新之前触发了获取,同时在显示警报时我们可以看到根据浏览器中呈现的文本"isChecked"在两个范围中具有相同的值.好吧,没什么大不了的,如果这就是"ng-change"的行为,那么就这样吧,我们总是$watch可以在那里设置并运行这个功能......但是让我们做另一个实验:

像这样:PLUNKER

.directive("testDirective", function () {
    return {
        restrict: 'E',
        scope: {
            isChecked: '=',
            doSomething: '&'
        },
        controller: function($scope){
          $scope.internalDoSomething = function(){alert("In the directive's scope is " + ($scope.isChecked?"checked!":"not checked"))};
        },
        template: '<label><input type="checkbox" ng-change="internalDoSomething()" ng-model="isChecked" /> Is it Checked?</label>'+
                  '<p>In the <b>directive\'s</b> scope <b>{{isChecked?"it\'s checked":"it isn\'t checked"}}</b>.</p>'
    };
}); 
Run Code Online (Sandbox Code Playgroud)

现在我们只是使用指令范围的函数来做与控制器范围的功能相同的事情,但这一次发现模型已经更新,所以在这一点似乎指令的范围已更新,但控制器的范围未更新......很奇怪!

让我们确保是这样的:PLUNKER

angular.module('testApp', [])
.controller('mainCtrl', function($scope) {
  $scope.isChecked = false;
  $scope.doingSomething = function(directiveIsChecked){
    alert("In the controller's scope is " + ($scope.isChecked?"checked!":"not checked") + "\n"
        + "In the directive's scope is " + (directiveIsChecked?"checked!":"not checked") );
  };
})
.directive("testDirective", function () {
    return {
        restrict: 'E',
        scope: {
            isChecked: '=',
            doSomething: '&'
        },
        controller: function($scope){
          $scope.internalDoSomething = function(){ $scope.doSomething({directiveIsChecked:$scope.isChecked}) }; 
        },
        template: '<label><input type="checkbox" ng-change="internalDoSomething()" ng-model="isChecked" /> Is it Checked?</label>'+
                  '<p>In the <b>directive\'s</b> scope <b>{{isChecked?"it\'s checked":"it isn\'t checked"}}</b>.</p>'
    };
}); 
Run Code Online (Sandbox Code Playgroud)

这次我们使用指令范围的函数来触发控制器的绑定函数,并且我们使用指令范围的值将参数传递给控制器​​的函数.现在在控制器的功能中,我们可以确认我们在上一步中已经怀疑的内容,即:隔离的范围首先被更新,然后ng-change被触发,并且在此之后,指令的范围的绑定得到更新.

现在,最后,我的问题:

  • 在执行任何其他操作之前,angularjs不应该同时更新所有绑定属性吗?
  • 任何人都可以给我详细解释内部发生的事情,以证明这种行为的合理性吗?

换句话说:如果在模型更新之前触发了"ng-change",我就能理解这一点,但是我很难理解在更新模型之后以及在完成填充更改之前触发函数绑定属性.

如果您读到这里:祝贺并感谢您的耐心等待!

何塞普

m59*_*m59 20

总结一下这个问题,ngModelController有一个过程要经过watches才会被解雇.您在处理更改$scope之前记录了外部属性,ngModelController并导致$ digest循环,这将反过来触发$watchers.model直到那时我才会考虑更新.

这是一个复杂的系统.我做了这个演示作为参考.我建议更改return值,键入和单击 - 只需以各种方式搞乱它并检查日志.这使得一切都很清楚.

演示(玩得开心!)

ngModelController 它有自己的函数数组作为对不同更改的响应运行.

ngModelController有两种"管道"用于确定如何处理某种变化.这些允许开发人员控制值的流动.

如果将scope属性指定为ngModel更改,则$formatter管道将运行.此管道用于确定应如何$scope在视图中显示来自的值,但仅保留模型.所以,ng-model="foo"$scope.foo = '123',通常会显示123在输入,但格式可以返回1-2-3或任何价值.$scope.foo仍然是123,但它显示为格式化程序返回的任何内容.

$parsers处理同样的事情,但相反.当用户键入内容时,将运行$ parser管道.无论$parser回报是什么,将会是什么ngModel.$modelValue.因此,如果用户键入abc$parser返回a-b-c,那么视图将不会更改,但$scope.foo现在是a-b-c.

无论是a $formatter还是run $parser,$validators都会运行.验证器使用的任何属性名称的有效性将由验证函数(truefalse)的返回值设置.

$viewChangeListeners在视图更改后触发,而不是模型更改.这个特别令人困惑,因为我们指的是$scope.foo和非ngModel.$modelValue.一个视图将不可避免地更新ngModel.$modelValue(除非在管道中被阻止),但这不是model change我们所指的.基本上,$viewChangeListeners是在之后$parsers而不是之后被解雇$formatters.因此,当视图值更改(用户类型)时,$parsers, $validators, then $viewChangeListeners.有趣的时间= D.

所有这些都发生在内部ngModelController.在此过程中,ngModel对象不会像您期望的那样更新.管道传递将影响该对象的值.在该过程结束时,ngModel将使用正确的$viewValue和更新对象$modelValue.

最后,ngModelController完成并且$digest将发生循环以允许应用程序的其余部分响应所得到的更改.

这是演示中的代码,万一发生任何事情:

<form name="form">
  <input type="text" name="foo" ng-model="foo" my-directive>
</form>
<button ng-click="changeModel()">Change Model</button>
<p>$scope.foo = {{foo}}</p>
<p>Valid: {{!form.foo.$error.test}}</p>
Run Code Online (Sandbox Code Playgroud)

JS:

angular.module('myApp', [])

.controller('myCtrl', function($scope) {

  $scope.foo = '123';
  console.log('------ MODEL CHANGED ($scope.foo = "123") ------');

  $scope.changeModel = function() {
    $scope.foo = 'abc';
    console.log('------ MODEL CHANGED ($scope.foo = "abc") ------');
  };

})

.directive('myDirective', function() {
  var directive = {
    require: 'ngModel',
    link: function($scope, $elememt, $attrs, $ngModel) {

      $ngModel.$formatters.unshift(function(modelVal) {
        console.log('-- Formatter --', JSON.stringify({
          modelVal:modelVal,
          ngModel: {
            viewVal: $ngModel.$viewValue,
            modelVal: $ngModel.$modelValue
          }
        }, null, 2))
        return modelVal;
      });

      $ngModel.$validators.test = function(modelVal, viewVal) {
        console.log('-- Validator --', JSON.stringify({
          modelVal:modelVal,
          viewVal:viewVal,
          ngModel: {
            viewVal: $ngModel.$viewValue,
            modelVal: $ngModel.$modelValue
          }
        }, null, 2))
        return true;
      };

      $ngModel.$parsers.unshift(function(inputVal) {
        console.log('------ VIEW VALUE CHANGED (user typed in input)------');
        console.log('-- Parser --', JSON.stringify({
          inputVal:inputVal,
          ngModel: {
            viewVal: $ngModel.$viewValue,
            modelVal: $ngModel.$modelValue
          }
        }, null, 2))
        return inputVal;
      });

      $ngModel.$viewChangeListeners.push(function() {
        console.log('-- viewChangeListener --', JSON.stringify({
          ngModel: {
            viewVal: $ngModel.$viewValue,
            modelVal: $ngModel.$modelValue
          }
        }, null, 2))
      });

      // same as $watch('foo')
      $scope.$watch(function() {
        return $ngModel.$viewValue;
      }, function(newVal) {
        console.log('-- $watch "foo" --', JSON.stringify({
          newVal:newVal,
          ngModel: {
            viewVal: $ngModel.$viewValue,
            modelVal: $ngModel.$modelValue
          }
        }, null, 2))
      });


    }
  };

  return directive;
})

;
Run Code Online (Sandbox Code Playgroud)

  • 真棒!非常感谢! (2认同)