外挂式插件编程思路【进阶篇】(5)
继续深造angular.js,并加入jquery.js
<!-- 空html,等待html插入 --> <div id="tab_body"></div>
本网页模拟弱代码、无代码模式后端自动生成的html
【demo.html】
<!DOCTYPE html> <html ng-app="myApp" ng-controller="myhtml"> <head> <meta charset="utf-8" /> <title>外挂式插件编程思路(进阶)</title> <script src="jquery.min.js"></script> <script src="angular.min.js"></script> <script src="app.js"></script> <style> dt { border: 1px rgba(0,0,0,0.05) solid; border-bottom:0; list-style: none; margin: 0; background: rgba(0,0,0,0.02); border-radius: 8px 8px 0px 0px; overflow: hidden; } dd { border: 1px rgba(0,0,0,0.05) solid; border-top:0; list-style: none; margin: 0; padding: 10px 10px 10px 10px; border-radius:0px 0px 8px 8px; } dt span { background: rgba(0,0,0,0.03); display: inline-block; height: 40px; line-height: 40px; padding: 0px 20px 0px 20px; cursor: pointer; border-left: 1px rgba(0,0,0,0.05) solid; } dt span:nth-child(1) {border-left:0px;} dt span.active { background:#ff0000; color:#fff; font-weight: bold; } </style> </head> <body> <!-- 空html,等待html插入 --> <div id="tab_body"></div> <script> //本网页模拟弱代码、无代码模式后端自动生成的html //加载tab html function load_tab_html() { let tab_html=` <h1>模拟tab切换</h1> <dl> <dt><span class="{{$index==tab.active_index ? 'active':''}}" ng-repeat="x in tab.list" ng-click="tab.change($index)">{{x.title}}</span></dt> <dd>{{tab.list[tab.active_index].content}}</dd> </dl> `; $("#tab_body").html(app.html(tab_html)); } var app=ng_app(); app.init(function() { //tab标签相关 app.$scope.tab={ active_index:0, list:[ {title:'首页',content:'首页内容'}, {title:'新闻',content:'新闻列表'}, {title:'产品',content:'产品列表'}, ], change:function(index){ console.log('change',index); if(app.$scope.tab.active_index!=index) app.$scope.tab.active_index=index; } }; load_tab_html(); app.update();//页面渲染 }); </script> </body> </html>
【app.js】
function ng_app() { var MyApp= { init:function(back) { console.log('init'); var me=this; var app = angular.module('myApp',[]); app.controller("myhtml",function($scope, $http,$window,$compile) { me.$scope=$scope; me.$http=$http; me.$window=$window; me.$compile=$compile; back(); }); } //更新模板渲染 优化ng频繁更新有报错,这里加1毫秒延迟 避免报错 ,update:function(){ var me=this; setTimeout(function(){ try{ me.$scope.$apply(); }catch(e){} },1); }, //配合jq使用,jq后的模板,重新渲染 html:function(html) { var that=this; try{ var result=that.$compile(html)(that.$scope); if(result.selector)//假设存在 this_tpl_new.selector 则认为ng变量不存在失败了 { //console.error(this_tpl_new.selector); var result=html; } }catch(e){ var result=html; } return result; }, new:function(){ return this; } } var result=MyApp.new(); return result; };
功能正常