我們先建立一個addScript函數,用於動態載入js指令碼。
/**
* 動態載入js檔案檔案
* @param url
* @param callback
*/
function addScript(url,callback){
var elt = document.createElement("script");
elt.src = url;
elt.anysc = true;
if(elt.onload==null){
elt.onload = function(){
typeof callback=='function'&&callback();
}
}else{
elt.onreadystatechange = function(){
if(elt.readyState=="loaded" || elt.readyState=="complete"){
typeof callback=='function'&&callback();
}
}
}
document.getElementsByTagName("body")[0].appendChild(elt);
}
然後寫angularjs指令
directivesApp.directive('ueditor',
function () {
return{
restrict: 'EA',
require: 'ngModel',
scope: {
height: '@?'
},
link: function (scope, element, attr, ctrl) {
var _self = this,
_initContent,
editor,
editorReady = false,
baseURL = "/assets/vendor/jquery_plugin/ueditor/1.4.3/"; //寫你的ue路徑
var fexUE = {
initEditor: function () {
var _self = this;
if (typeof UE != 'undefined') {
editor = new UE.ui.Editor({
initialContent: _initContent,
toolbars: [
['source', 'undo', 'redo', 'bold', 'italic', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote',
'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist']
],
initialFrameHeight:scope.height || 120,
autoHeightEnabled:false,
wordCount:false,
elementPathEnabled: false
});
editor.render(element[0]);
editor.ready(function () {
editorReady = true;
_self.setContent(_initContent);
editor.addListener('contentChange', function () {
scope.$apply(function () {
ctrl.$setViewValue(editor.getContent());
});
});
});
} else {
addScript(baseURL + 'ueditor.config.js');
addScript(baseURL + 'ueditor.all.min.js', function(){
_self.initEditor();
})
}
},
setContent: function (content) {
if (editor && editorReady) {
editor.setContent(content);
}
}
};
/**
* 當Model改變值得時候賦值。
*/
ctrl.$render = function () {
_initContent = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
fexUE.setContent(_initContent);
};
fexUE.initEditor();
}
}
}
)
好了,ue的封裝就完成了。
關於ue的寬度不能100%的問題,我在我項目中css中寫了如下:
/*修證百度的寬度100%問題*/
#edui1{width:100% !important; margin-bottom: 10px;}/* 這個ID為編輯器的ID */
#edui1_iframeholder{width:100% !important}/* 這個ID為編輯器可編輯區域的ID */