首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >解释ngModel管道、解析器、格式化程序、viewChangeListeners和$watchers的顺序

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

Stack Overflow用户
提问于 2014-09-11 02:33:36
回答 1查看 7.3K关注 0票数 10

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

考虑一下这个简单的angularjs apphttp://plnkr.co/edit/QDVZTf9Cx2qNhU1GAhuo?p=preview

代码语言:javascript
复制
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:

代码语言:javascript
复制
  <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中,我们实例化"testDirective“在"mainCtrl”中,并将"mainCtrl“作用域的"isChecked”属性与指令独立作用域的"isChecked“属性绑定。
  • 该指令呈现一个复选框,该复选框将"isChecked“scope属性作为模型。
  • 当我们选中或取消选中复选框时,我们可以看到两个作用域的两个属性同时更新。

到现在为止还好。

现在让我们做一些小小的改变,就像这样:http://plnkr.co/edit/KvjwvYGcVpVJjfbjHzex?p=preview

代码语言:javascript
复制
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>'
    };
}); 

这是:

代码语言:javascript
复制
<!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更改”中触发该函数。

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

像这样:http://plnkr.co/edit/JB3IOcM33g43kxBm66YT?p=preview

代码语言:javascript
复制
.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>'
    };
}); 

现在我们只是使用指令作用域的一个函数来做与控制器作用域的函数相同的事情,但是这次发现模型已经被更新了,所以在这个时候,指令的范围似乎被更新了,但是控制器的范围没有被更新.奇怪!

让我们确定情况是这样的:http://plnkr.co/edit/fl5YYQVYoZNHBdXbCb5Q?p=preview

代码语言:javascript
复制
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-更改”,我可以理解,但我很难理解,在更新模型之后,在填充绑定属性的更改之前,函数会被触发。

如果你读了这么多:恭喜你,谢谢你的耐心!

乔塞普

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-09-11 19:55:05

总之,在启动ngModelController之前,watches需要经过一个过程。在$scope处理更改并导致$digest循环之前,您正在记录外部$digest属性,这反过来会触发$watchers。在此之前,我不会考虑更新model

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

演示(玩得开心!)

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

ngModelController有两种“管道”来决定如何处理一种变化。这些允许开发人员控制值的流。

如果指定为ngModel的scope属性发生更改,则$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

在运行$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循环,以允许应用程序的其余部分响应所产生的更改。

下面是演示中的代码,以防发生任何事情:

代码语言:javascript
复制
<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>

联署材料:

代码语言:javascript
复制
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;
})

;
票数 21
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25778149

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档