angular1学习笔记,view model 的同步过程
事情起源于在项目中遇到的一个小问题:项目中需要一个输入框输入卖出产品数量,并且在用户输入后根据输入数据计算手续费。很自然的我用了ng-model和ng-change,并且一般情况下没什么问题。问题是:输入框下还有一个按钮是全部卖出,点击这个按钮程序会自动设置卖出额。但实际上这时程序并没有计算手续费。 var ngChangeDirective = valueFn({ restrict: 'A',require: 'ngModel',link: function(scope,element,attr,ctrl) { ctrl.$viewChangeListeners.push(function() { scope.$eval(attr.ngChange); }); } }); 从中我们也可以看出ng-change只做了view到model的监听。所以当我们直接在js中修改ng-model的变量时并不会触发ng-change。 function setupModelWatcher(ctrl) { // model -> value // !!!Note: we cannot use a normal scope.$watch as we want to detect the following: // !!!1. scope value is 'a' // !!! 2. user enters 'b' // !!!3. ng-change kicks in and reverts scope value to 'a' // -> scope value did not change since the last digest as // ng-change executes in apply phase // !!!4. view should be changed back to 'a' ctrl.$$scope.$watch(function ngModelWatch(scope) { var modelValue = ctrl.$$ngModelGet(scope); // if scope model value and ngModel value are out of sync // This cannot be moved to the action function,because it would not catch the // case where the model is changed in the ngChange function or the model setter if (modelValue !== ctrl.$modelValue && // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator // eslint-disable-next-line no-self-compare (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue) ) { ctrl.$$setModelValue(modelValue); } return modelValue; }); } 里面的注释解释了为什么变量model值的修改要在ng-change之后,因为ng-change中很可能会把变量的值又修改回去,这样变量值事实上就并没改变(写api真的是什么情况都要考虑到啊!!)。关于这一点,以及前面的问题这里有一个demo代码:http://runjs.cn/code/wnmdzvwg 既然看源码没什么收获,那么就去网上搜搜文章看看吧。这个过程中找到一篇很好的文章,这篇文章介绍了
在学习 However,custom controls might also pass objects to this method. In 从上面也可以看到其实一个变量的更新由view到model和model到view不止 在查了一圈资料后找到一个很清晰的解释:https://stackoverflow.com/que...,大家其实只需要看问题的回答,问题实在太长了。。。 从view到model: 本文没有具体介绍 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |