Maison > interface Web > js tutoriel > le corps du texte

Directive dans AngularJS pour personnaliser une table_AngularJS

WBOY
Libérer: 2016-05-16 15:18:17
original
1095 Les gens l'ont consulté

Permettez-moi d'abord de vous expliquer les exigences du formulaire :

● Structure du tableau

<table>
<thead>
<tr>
<th>Name</th>
<th>Street</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>></td>
<td>></td>
<td>></td>
</tr>
</tbody>
</table>
<div>4行</div>
Copier après la connexion

● Cliquez sur un ième pour trier la colonne
● Vous pouvez donner un alias à l'en-tête
● Vous pouvez définir si une certaine colonne est affichée
● Il y a une ligne sous le tableau indiquant le nombre total de lignes

Nous voulons que le tableau ressemble à ceci :

<table-helper datasource="customers" clumnmap="[{name: 'Name'}, {street: 'Street'}, {age: 'Age'}, {url: 'URL', hidden: true}]"></table-helper>
Copier après la connexion

Ci-dessus, la source de données de la source de données provient de $scope.customers dans le contrôleur, qui est à peu près au format {nom : 'David', rue : '1234 Anywhere St.', âge : 25, url : 'index .html'} , les détails sont omis.

columnmap est responsable de l'alias des colonnes et de décider si une colonne doit être affichée.

Comment y parvenir ?

La directive ressemble à peu près à ceci :

var tableHelper = function(){
var template = '',
link = function(scope, element, attrs){
}
return {
restrict: 'E',
scope: {
columnmap: '=',
datasource: '='
},
link:link,
template:template
}; 
}
angular.module('directiveModule')
.directive('tableHelper', tableHelper); 
Copier après la connexion

Plus précisément,

Tout d'abord, surveillez les modifications dans la source de données. Une fois qu'il y a des modifications, rechargez la table.

scope.$watchCollection('datasource', render);
//初始化表格
function render(){
if(scope.datasource && scope.datasource.length){
table += tableStart;
table += renderHeader();
table += renderRows() + tableEnd;
//加载统计行
renderTable();
}
} 
Copier après la connexion

Le chargement du tableau est grossièrement divisé en trois étapes : le chargement de l'en-tête du tableau, le chargement du corps du tableau et le chargement des lignes statistiques.

//加载头部
function renderHeader(){
var tr = '<tr>';
for(var prop in scope.datasource[0]){
//{name: 'David',street: '1234 Anywhere St.',age: 25,url: 'index.html'}
//根据原始列名获取别名,并考虑了是否显示列的情况
var val = getColumnName(prop);
if(val){
//visibleProps存储的是原始列名
visibleProps.push(prop);
tr += '<th>' + val + '</th>';
}
}
tr += '</tr>';
tr = '<thead>' + tr '</thead>';
return tr;
}
//加载行
function renderRows(){
var rows = '';
for(var i = 0, len = scope.datasource.length; i < len; i++){
rows += '<tr>';
var row = scope.datasource[i];
for(var prop in row){
//当前遍历的原始列名是否在visibleProps集合中,该集合存储的是原始列名
if(visibleProps.indexOf(prop) > -1){
rows += '<td>' + row[prop] + '</td>';
}
}
rows += '</tr>';
}
rows = '<tbody>' + rows + '</tbody>';
return rows;
}
//加载统计行
function renderTable(){
table += '<br /><div class="rowCount">' + scope.datasource.length + '行</div>';
element.html(table);
table = '';
} 
Copier après la connexion

Lors du chargement de l'en-tête du tableau, une méthode est utilisée pour obtenir l'alias basé sur le nom de la colonne d'origine.

//根据原始列名获取列的别名,并考虑是否隐藏列的情况
function getColumnName(prop){
if(!scope.columnmap) return prop;
//得到[{name: 'Name'}]
var val = filterColumnMap(prop);
if(val && val.length && !val[0].hidden) return val[0][prop];
else return null;
}
Copier après la connexion

Dans la méthode getColumnName, une colonne basée sur le nom de colonne d'origine est utilisée

//比如根据name属性,这里得到[{name: 'Name'}]
//[{name: 'Name'}, {street: 'Street'}, {age: 'Age'}, {url: 'URL', hidden: true}]
function filterColumnMap(prop) {
var val = scope.columnmap.filter(function(map) {
if (map[prop]) {
return true;
}
return false;
});
return val;
}
Copier après la connexion

Le code spécifique est le suivant :

(function(){
var tableHelper = fucntion(){
var template = '
', link = function(scope, element, attrs){ var headerCols = [], //表头列们 tableStart = '', tableEnd = '
', table = '', visibleProps = [],//可见列 sortCol = null,//排序列 sortDir =1; //监视集合 sscope.$watchCollection('datasource', render); //给表头th绑定事件 wireEvents(); //初始化表格 function render(){ if(scope.datasource && scope.datasource.length){ table += tableStart; table += renderHeader(); table += renderRows() + tableEnd; //加载统计行 renderTable(); } } //给th添加click事件 function wireEvents() { element.on('click', function(event){ if(event.srcElement.nodeName === 'TH'){ //获取列的名称 var val = event.srcElement.innerHTML; //根据列的别名获取原始列名 var col = (scope.columnmap) ? getRawColumnName(val) : val; if(col){ //对该列进行排序 sort(col); } } }); } //给某列排序 function sort(col){ if(sortCol === col){ sortDir = sortDir * -1; } sortCol = col; scope.datasource.sort(function(a,b){ if(a[col] > b[col]) return 1 * sortDir; if(a[col] < b[col]) return -1 * sortDir; return 0; }); //重新加载表格 render(); } //加载头部 function renderHeader(){ var tr = ''; for(var prop in scope.datasource[0]){ //{name: 'David',street: '1234 Anywhere St.',age: 25,url: 'index.html'} //根据原始列名获取别名,并考虑了是否显示列的情况 var val = getColumnName(prop); if(val){ //visibleProps存储的是原始列名 visibleProps.push(prop); tr += '' + val + ''; } } tr += ''; tr = '' + tr ''; return tr; } //加载行 function renderRows(){ var rows = ''; for(var i = 0, len = scope.datasource.length; i < len; i++){ rows += ''; var row = scope.datasource[i]; for(var prop in row){ //当前遍历的原始列名是否在visibleProps集合中,该集合存储的是原始列名 if(visibleProps.indexOf(prop) > -1){ rows += '' + row[prop] + ''; } } rows += ''; } rows = '' + rows + ''; return rows; } //加载统计行 function renderTable(){ table += '
' + scope.datasource.length + '行
'; element.html(table); table = ''; } //根据列的别名获取原始列名 function getRawColumnName(friendlyCol) { var rawCol; //columnmap =[{name: 'Name'}, {street: 'Street'}, {age: 'Age'}, {url: 'URL', hidden: true}] scope.columnmap.forEach(function(colMap) { //{name: 'Name'} for (var prop in colMap) { if (colMap[prop] === friendlyCol) { rawCol = prop; break; } } return null; }); return rawCol; } function pushColumns(rawCol, renamedCol) { visibleProps.push(rawCol); scope.columns.push(renamedCol); } //比如根据name属性,这里得到[{name: 'Name'}] //[{name: 'Name'}, {street: 'Street'}, {age: 'Age'}, {url: 'URL', hidden: true}] function filterColumnMap(prop) { var val = scope.columnmap.filter(function(map) { if (map[prop]) { return true; } return false; }); return val; } //根据原始列名获取列的别名,并考虑是否隐藏列的情况 function getColumnName(prop){ if(!scope.columnmap) return prop; //得到[{name: 'Name'}] var val = filterColumnMap(prop); if(val && val.length && !val[0].hidden) return val[0][prop]; else return null; } }; return { restrict: 'E', scope: { columnmap: '=', datasource: '=' }, link:link, template:template }; }; angular.module('directiveModule') .directive('tableHelper', tableHelper); }());
Copier après la connexion

Ce qui précède représente les connaissances partagées par l'éditeur sur la personnalisation d'une table à l'aide de Directive dans AngularJS. J'espère que cela vous sera utile.

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!