外挂式插件编程思路【进阶篇】(4)
外挂式编程结合angular.js
【demo.html】
<!DOCTYPE html>
<html ng-app="myApp" ng-controller="myhtml">
<head>
<meta charset="utf-8" />
<title>外挂式插件编程思路(进阶)</title>
<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>
<div>
<h1>双向绑定</h1>
<input type="text" ng-model="value1"><span>您输入的内容是{{value1}}</span>
</div>
<div>
<h1>当前时间</h1>
<span>{{now_time}}</span>
</div>
<div>
<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>
</div>
<script>
/**
*本网页 将外挂插法综合运用,内外插结合。
*var app=ng_app();app变量具备了 angualr.js的语法,如果需要更多直接挂载到app上
*app里的init通过callback的方式,让外部的回调可以支持angualr.js的语法
*/
//定时更新当前时间
function update_now_time()
{
app.$scope.now_time=(new Date()).toLocaleString();
app.update();//页面渲染
setTimeout(()=>{
update_now_time();
},1000);
}
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;
}
};
update_now_time();//执行 定时更新当前时间
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);
},
new:function(){
return this;
}
}
var result=MyApp.new();
return result;
};外挂式开发原理,配合angular.js 实现一些功能可以在外部使用。因为js里对象是双向绑定的,破开了官方文档一些固定格式的约束。为后面的低代码模式提供良好的场景。





