AngularJS學(xué)習(xí)筆記(三)數(shù)據(jù)雙向綁定的簡單實(shí)例
雙向綁定
雙向綁定是AngularJS最實(shí)用的功能,它節(jié)省了大量的代碼,使我們專注于數(shù)據(jù)和視圖,不用浪費(fèi)大量的代碼在Dom監(jiān)聽、數(shù)據(jù)同步上,關(guān)于雙向更新,可看下圖:
數(shù)據(jù)-->視圖
這里我們只演示有了數(shù)據(jù)以后,如何綁定到視圖上。
<!DOCTYPE html> <html ng-app="App"> <head> <script type="text/javascript" src="http://sandbox.runjs.cn/uploads/rs/394/xjz9g1bv/angular.js"></script> <script type="text/javascript"> var App = angular.module("App", []); App.controller("ctrl", function ($scope) { $scope.username='張三' $scope.changename=function(){ $scope.username='李四'; } }); </script> </head> <body> <div ng-controller ="ctrl"> <button class='btn btn-primary' ng-click='changename();'> username='李四' </button> <!--頁面加載初期,用戶可能會看到綁定的表達(dá)式--> <div>{{username}}</div> <!--此綁定不會出現(xiàn)上述情況--> <div ng-bind='username'></div> </div> </body> </html>
點(diǎn)擊按鈕之后,div內(nèi)容變成 李四,效果如圖:
視圖—>數(shù)據(jù)
上個(gè)例子,我們看了數(shù)據(jù)變化后,視圖也會自動變化。那么這個(gè)例子則是反過來,視圖變化,導(dǎo)致數(shù)據(jù)也跟著變化,那么數(shù)據(jù)變化后,我們?nèi)绾沃滥?,這兒我們可以通過另外一個(gè)元素將數(shù)據(jù)再顯示出來。
<!DOCTYPE html> <html ng-app="App"> <head> <script type="text/javascript" src="http://sandbox.runjs.cn/uploads/rs/394/xjz9g1bv/angular.js"></script> <script type="text/javascript"> var App = angular.module("App", []); App.controller("ctrl", function ($scope) { $scope.username='張三' }); </script> </head> <body> <div ng-controller ="ctrl"> <input type='text' ng-model='username' /> <div>{{username}}</div> </div> </body> </html>
查看效果:
實(shí)現(xiàn)機(jī)制
angular對常用的dom事件,xhr事件等做了封裝, 在里面觸發(fā)進(jìn)入angular的digest流程。
在digest流程里面, 會從rootscope開始遍歷, 檢查所有的watcher。
- javascript實(shí)現(xiàn)數(shù)據(jù)雙向綁定的三種方式小結(jié)
- Vue.js每天必學(xué)之?dāng)?shù)據(jù)雙向綁定
- 輕松實(shí)現(xiàn)javascript數(shù)據(jù)雙向綁定
- 深入學(xué)習(xí)AngularJS中數(shù)據(jù)的雙向綁定機(jī)制
- 淺談AngularJs 雙向綁定原理(數(shù)據(jù)綁定機(jī)制)
- Vue.js第一天學(xué)習(xí)筆記(數(shù)據(jù)的雙向綁定、常用指令)
- 深入理解Angularjs向指令傳遞數(shù)據(jù)雙向綁定機(jī)制
- JS原生數(shù)據(jù)雙向綁定實(shí)現(xiàn)代碼
- 實(shí)例剖析AngularJS框架中數(shù)據(jù)的雙向綁定運(yùn)用
- js實(shí)現(xiàn)數(shù)據(jù)雙向綁定(訪問器監(jiān)聽)
相關(guān)文章
AngularJS頁面訪問時(shí)出現(xiàn)頁面閃爍問題的解決
這篇文章主要介紹了AngularJS框架使用中出現(xiàn)頁面閃爍問題的解決方法,閃爍問題一般是初始化未加載完畢造成的,需要的朋友可以參考下2016-03-03Ionic+AngularJS實(shí)現(xiàn)登錄和注冊帶驗(yàn)證功能
這篇文章主要介紹了Ionic+AngularJS實(shí)現(xiàn)登錄和注冊帶驗(yàn)證功能,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-02-02AngularJS定時(shí)器的使用與移除操作方法【interval與timeout】
這篇文章主要介紹了AngularJS定時(shí)器的使用與移除操作方法,結(jié)合實(shí)例形式分析了AngularJS中interval與timeout方法的相關(guān)使用技巧,需要的朋友可以參考下2016-12-12