AngularJS实现Model缓存的方式_AngularJS.docAngularJS实现Model缓存的方式在AngularJS中如何实现一个Model的缓存呢?可以通过在Provider返回一个构造函数,并在构造函数屮设计一个缓存字段,在本篇末尾将引出这种做法。一般來说,Model要赋值给Scope的某个变量。有的直接把对象赋值给Scope变量;有的在Provider屮返回一个对象再赋值给Scope变量;有的在Provider中返冋一个构造函数再赋值给Scope变量。木篇来 体验。首先自定义一个directive,用來点击按钮改变一个scope变量值。angularmoduleCapp",[])directive(,updater",function(){reutrn{scope:{user:V},,,template:'<button>ChangeUser,datatowhaaaat?</button>",link:function(scope,element,attrs){(,click,,function(){,data='whaaaat?‘;scope.$apply();})}■给Scope变量赋值一个对象controllerFirstCtrl",function(){varfirst二this;{data:'cool"};})controller(5SecondCtrl5,function(){varsecond二this;second,user二{data:'cool'};})页而屮:<divng-controller=,zFirstCtrrz>{{user,data)}〈inputng~model=/,,><divupdateruser二〃uscr〃>〈/div></div><divng~control1er二〃SecondCtrl〃>{{user,data}}<inputng-modcl二〃user,dotaz,><divupdateruser=//user,z></div></div>以上,•改变FirstCtrl中input的值,仅仅影响FirstCtrl中的变量user,不影响SecondCtrl中的变量user•点击FirstCtrl中的按钮,仅仅影响FirstCtrl中的变量user•改变SecondCtrl中的input的值,仅仅影响SecondCtrl中的变量user,不影响FirstCtrl中的变量user•点击SecondCtrl中的按钮,仅仅影响SecondCtrl中的变量user■在Provider返回一个对象,赋值给Scope变量controller(,ThirdCtrl,,['User',function(User){vartbird二this;third,user二User;}])controller(5FourthCtrT,['User',function(User){varfourth二this;;}])//provider返回对彖provider(5User',function(){this.$get二function(){return{data:'cool,}};})页而屮:<divng-control1er=zzThirdCtrlz,>{{user
AngularJS实现Model缓存的方式 AngularJS 来自淘豆网www.taodocs.com转载请标明出处.