angularjs的双向绑定原理实现
生活随笔
收集整理的這篇文章主要介紹了
angularjs的双向绑定原理实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
angularjs的雙向綁定用js代碼來實現
<!DOCTYPE html> <html> <head><meta charset="utf-8" /><title>雙向綁定的js實現</title><script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script></head> <body><input type="text" id="txt1" /><input type="text" id="txt2" /><script type="text/javascript">window.onload = function () {let a = '';let oTxt = document.getElementById('txt1');let oTxt2 = document.getElementById("txt2");function $interval(fn, time) {setInterval(function () {fn();apply();}, time);}function $http(url, success, error) {$.ajax({url,dataType: 'json',success(result) {success(result);apply();},error});}//數據->inputfunction apply() {oTxt.value = a;oTxt2.value = a;}//$interval(function () {// a +='|';//}, 100);//$.ajax({// url: 'Data/1.txt',// dataType: 'json',// success(res) {// a = res;// apply();// },// error() {// alert("錯了");// }//});//$http('Data/1.txt', function (arr) {// a = arr;//}, function () {// alert('錯了');//});//setInterval(function () {// a += '|';// apply();//}, 100);//input->數據 oTxt.oninput = function () {a = this.value;apply();}oTxt2.oninput = function () {a = this.value;apply();}setInterval(function () {console.log(a);}, 100);}</script></body> </html>?
升級版的(封裝了一下)
<!DOCTYPE html> <html> <head><meta charset="utf-8" /><title>angularjs的雙向綁定實現</title><script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> </head> <body><input type="text" ng-model="a" /><input type="text" ng-model="a" /><select ng-model="a"><option value="1">北京</option><option value="2">上海</option><option value="3">廣州</option><option value="4">深圳</option></select><br /><br /><br /><br /> <br /><br /> <br /><br /><input type="text" ng-model="b" /><select ng-model="b"><option value="1">北京</option><option value="2">上海</option><option value="3">廣州</option><option value="4">深圳</option></select><script type="text/javascript">window.onload = function () {let $scope = {};let aEle = document.getElementsByTagName('*');//數據->inputfunction apply() {Array.from(aEle).forEach(ele => {let model = ele.getAttribute('ng-model');if (model) {if ($scope[model]) {ele.value = $scope[model];}else {ele.value = '';}}});}//input->數據 Array.from(aEle).forEach(ele => {let model = ele.getAttribute('ng-model');if (model) {ele.oninput = function () {$scope[model] = this.value;apply();}}});}</script> </body> </html>?
轉載于:https://www.cnblogs.com/zhumeiming/p/9820671.html
總結
以上是生活随笔為你收集整理的angularjs的双向绑定原理实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 简单的数据检索
- 下一篇: 【2018.10.20】noip模拟赛D