熟悉 Angular 的同学应该 都知道 Angular 最大的特点之一是:双向数据绑定,接下来我们模拟一下其过程
数据到 html 视图
- 我们想要实现的是 :数据变了,视图跟着变
- 简单分析一下,这个是比较容易解决的,可以使用下面的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| <script> //数据改变 导致 html元素改变 //页面中存在一个元素 <input id="input1"> window.onload = function () { let input1 = document.getElementById('input1'); let a = ''; //模拟 angular 中的 $interval 依赖 function $interval(fn,time) { setInterval(function () { fn(); apply(); },time); }
//数据 》 input,也就是更新数据 到页面 function apply () { input1.value = a; } $interval(function () { a += "|"; },100); }; </script>
|
html 视图 到 数据
较完整的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>手写angular的双向数据绑定</title> <script> window.onload = function () { let $scope = {}; let ele = document.getElementsByTagName('*');
//数据 》 页面元素 每次元素上发生了input 事件 就去更新一下 function apply () { Array.from(ele).forEach((item,index,arr)=>{ let mod = item.getAttribute('ng-model'); if (mod) { if ($scope[mod]) { item.value = $scope[mod]; } else { item.value = ''; } } }); } //为有 ng-model属性 的标签 添加 input 事件,当输入改变时就去改变 $scope上面的 数据 Array.from(ele).forEach((item,index,arr)=>{ let model=item.getAttribute('ng-model'); if (model) { item.oninput = function () { $scope[model] = this.value; apply(); }; } }); }; </script> </head> <body> <input ng-model="a" /> <input ng-model="a" /> <select ng-model="a"> <option value="1">北京</option> <option value="2">上海</option> <option value="3">深圳</option> </select> </body> </html>
|
结果示例
双向数据绑定
最后更新时间:
这里可以写作者留言,标签和 hexo 中所有变量及辅助函数等均可调用,示例:
http://love.haozigege.com/2018/05/12/angular-ng-model/