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

时间:2014-09-11 02:33:36

标签: 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>'
    };
}); 

使用这个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>

该应用:

  • 有一个控制器叫做:“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>'
    };
}); 

和此:

<!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>

我们唯一做的就是:

  • 在控制器范围内定义一个函数,该函数执行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>'
    };
}); 

现在我们只是使用指令范围的函数来执行与控制器范围的功能相同的事情,但这次事实证明模型已经更新,所以它似乎此时指令的范围已更新,但控制器的范围未更新......很奇怪!

让我们确保是这种情况: 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>'
    };
}); 

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

现在,最后,我的问题:

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

换句话说:如果在模型更新之前触发了“ng-change”,我就能理解,但是我很难理解在更新模型之后和完成之前触发了一个函数填充绑定属性的更改。

如果你读到这一点:祝贺并感谢你的耐心等待!

何塞普

1 个答案:

答案 0 :(得分:19)

要总结问题,ngModelController有一个流程要在watches被解雇之前完成。您在$scope处理了更改之前记录了外部ngModelController媒体资源,并导致$摘要周期,而这又会引发$watchers。在此之前,我不会认为model已更新。

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

Demo (have fun!)

ngModelController拥有自己的函数数组作为对不同更改的响应。

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

如果分配为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。< / p>

运行$formatter$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>

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;
})

;