AngularJS 裡最能發揮威力的一塊,莫過於自訂指令(directive)。它把「DOM 操作」這件骯髒事收攏在一個邊界清楚的容器裡,讓其餘程式碼都能維持宣告式的風格。本文整理三個實際專案中常用的指令寫法:兩個富文本編輯器與一個表格元件,並說明背後需要留意的細節。
以下範例都搭配 oclLazyLoad 做延遲載入,也就是等到指令真正被編譯時,才把對應的第三方 JS 拉進來,避免首頁被一堆用不到的腳本拖慢。
關鍵在於「 bidirectional 綁定」:編輯器內容改變時要推回 Angular 的 model,model 變動時又要反映回編輯器。前者靠 ctrl.$setViewValue(),後者則要覆寫 ctrl.$render。
angular.module('AdminApp').directive('uiKindeditor', ['uiLoad', function (uiLoad) {
return {
restrict: 'EA',
require: '?ngModel',
link: function (scope, element, attrs, ctrl) {
uiLoad.load('../Areas/AdminManage/Content/Vendor/jquery/kindeditor/kindeditor-all.js').then(function () {
var _initContent, editor;
var fexUE = {
initEditor: function () {
editor = KindEditor.create(element[0], {
width: '100%',
height: '400px',
resizeType: 1,
uploadJson: '/Upload/Upload_Ajax.ashx',
formatUploadUrl: false,
allowFileManager: true,
afterChange: function () {
ctrl.$setViewValue(this.html());
}
});
},
setContent: function (content) {
if (editor) {
editor.html(content);
}
}
};
if (!ctrl) {
return;
}
_initContent = ctrl.$viewValue;
ctrl.$render = function () {
_initContent = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
fexUE.setContent(_initContent);
};
fexUE.initEditor();
});
}
}
}]);
這裡有兩個實務上的提醒:require: '?ngModel' 的问號代表 ngModel 是選配,指令裡再用 if (!ctrl) return; 保護一次,可以大幅降低「忘記掛 ng-model 就整頁爆掉」的風險。另外 ctrl.$isEmpty() 用來把 undefined 正規化成空字串,避免把 "undefined" 字面寫進編輯器。
UEditor 的情況多了一層非同步:它必須等 editor.ready() 之後才能安全地寫入內容,否則會拿到空白。因此這裡額外用一個 editorReady 旗標把關。
另外,UEditor 的 contentChange 事件是在 Angular 的 digest 週期之外觸發的,所以必須包在 scope.$apply() 裡,否則畫面不會更新,甚至會丟出「digest already in progress」的錯誤。
angular.module("AdminApp").directive('uiUeditor', ["uiLoad", "$compile", function (uiLoad, $compile) {
return {
restrict: 'EA',
require: '?ngModel',
link: function (scope, element, attrs, ctrl) {
uiLoad.load(['../Areas/AdminManage/Content/Vendor/jquery/ueditor/ueditor.config.js',
'../Areas/AdminManage/Content/Vendor/jquery/ueditor/ueditor.all.js']).then(function () {
var _initContent, editor, editorReady = false;
var fexUE = {
initEditor: function () {
var _self = this;
if (typeof UE != 'undefined') {
editor = new UE.ui.Editor({
initialContent: _initContent,
autoHeightEnabled: false,
autoFloatEnabled: false
});
editor.render(element[0]);
editor.ready(function () {
editorReady = true;
_self.setContent(_initContent);
editor.addListener('contentChange', function () {
scope.$apply(function () {
ctrl.$setViewValue(editor.getContent());
});
});
});
}
},
setContent: function (content) {
if (editor && editorReady) {
editor.setContent(content);
}
}
};
if (!ctrl) {
return;
}
_initContent = ctrl.$viewValue;
ctrl.$render = function () {
_initContent = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
fexUE.setContent(_initContent);
};
fexUE.initEditor();
});
}
};
}]);
表格元件的難點不在初始化,而在「dataTable 自行重繪 DOM」這件事。Angular 不知道那些新產生的節點從哪來,於是我們必須在 fnRowCallback 裡手動呼叫 $compile(nRow)($scope),讓每一列產生的內容重新被 Angular 編譯,雙向綁定才會復活。
這個指令另外對外開放了兩個方法:getChooseData() 用來收集勾選列的識別碼,refreshTable() 則先清空資料再重繪,常用於「新增一筆後刷新列表」的情境。
angular.module('AdminApp').directive('uiDatatable', ['uiLoad', '$compile', function (uiLoad, $compile) {
return function ($scope, $element, attrs) {
$scope.getChooseData = function () {
var listID = "";
var chooseData = $element.find("input[name = IsChoose]:checkbox:checked");
if (chooseData.length > 0) {
for (var i = 0; i < chooseData.length; i++) {
listID += chooseData[i].value + ",";
}
}
return listID.substring(0, listID.length - 1);
};
$scope.refreshTable = function () {
$scope.dataTable.fnClearTable(0);
$scope.dataTable.fnDraw();
};
uiLoad.load(['../Areas/AdminManage/Content/Vendor/jquery/datatables/jquery.dataTables.min.js',
'../Areas/AdminManage/Content/Vendor/jquery/datatables/dataTables.bootstrap.js',
'../Areas/AdminManage/Content/Vendor/jquery/datatables/dataTables.bootstrap.css']).then(function () {
var options = {};
if ($scope.dtOptions) {
angular.extend(options, $scope.dtOptions);
}
options["processing"] = false;
options["info"] = false;
options["serverSide"] = true;
options["language"] = {
"processing": '正在加載...',
"lengthMenu": "每頁顯示 _MENU_ 條記錄數",
"zeroRecords": '<div style="text-align:center;font-size:12px">沒有找到相關數據</div>',
"info": "當前顯示第 _PAGE_ 頁 共 _PAGES_ 頁",
"infoEmpty": "空",
"infoFiltered": "搜索到 _MAX_ 條記錄",
"search": "搜索",
"paginate": {
"first": "首頁",
"previous": "上一頁",
"next": "下一頁",
"last": "末頁"
}
};
options["fnRowCallback"] = function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
$compile(nRow)($scope);
};
$scope.dataTable = $element.dataTable(options);
});
$element.find("thead th").each(function () {
$(this).on("click", "input:checkbox", function () {
var that = this;
$(this).closest('table').find('tr > td:first-child input:checkbox').each(function () {
this.checked = that.checked;
$(this).closest('tr').toggleClass('selected');
});
});
})
}
}]);
第一,把第三方函式庫的載入交給 uiLoad,指令的職責會乾淨很多。第二,凡是「非 Angular 世界」回呼的函式,都要記得進 $apply。第三,凡是「非 Angular 世界」產生的 DOM,都要記得 $compile。掌握這三點,jQuery 生態與 Angular 混用就不再是夢魘。
以上三個指令屬於拋磚引玉,實際專案裡通常還要加上銷毀時的資源清理(例如 scope.$on('$destroy', ...) 中呼叫編輯器的 remove()),以避免路由切換後殘留幽靈實例。