angular框架中提供了很多有效的指令,指令的目的就是为了提高代码的复用率,提高工作效率。
下面我们自己来定义一个指令:
一点建议:写指令名字的时候,尽量不要用用大写,下划线等,否则会有很大的坑等着你来踩
指令文件的结构:
js/directives/table
table.html
table.js table.js
define(['app'], function (myapp) {
myapp
.directive('dirtable', [function () {
return {
scope:{
"datasource": "=",
"option":"="
},
restrict: 'AE',
templateUrl: 'js/directives/table/table.html',
link: function (s, element, attrs) {
//监听值的改变,避免js执行顺序的影响(特别的当存在异步加载数据的时候)
s.$watchGroup(['datasource','option'], function (n_value) {
if (n_value) {
s.add_item=n_value[0];
s.n_option=n_value[1];
}
})
}
}
}])
}) table.html:
<table style="width:100%;">
<thead>
<tr class="">
<th ng-repeat="titlename in n_option.title" width="{{titlename.wid}}"> {{titlename.name}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="tmp in add_item track by $index">
<td ng-repeat="title in n_option.title" width="title.wid">{{tmp[title.key]}}</td>
</tr>
</tbody>
</table>
控制器中代码:
s.asd=[];
s.qwe={
title:[
{name:'序号',key:'order',wid:'97'},
{name:'姓名',key:'realname',wid:'123'},
{name:'手机号',key:'phone',wid:'150'},
{name:'邮箱',key:'email',wid:'198'},
{name:'角色',key:'rolename',wid:'142'},
{name:'所属部门',key:'departmentname',wid:'142'},
{name:'创建人',key:'createduser',wid:'114'},
{name:'创建时间',key:'created_at',wid:'160'},
{name:'操作',key:'pno',wid:'228'},
]
};
Html:
<dirtable datasource="asd" option="qwe"></dirtable>