AngularJS+ckEditor管理ng-model

时间:2023-03-08 21:35:43

1、首先去ckeditor的官网下载ckeditor包,http://ckeditor.com/download;

2、把ckeditor文件夹放入工程中(webapp文件夹下能访问到的都行)。

3、页面导入ckeditor.js,就导入这个文件即可。

4、使用Angular的directive配置ckeditor编辑器

/**ckEditor,因为这里定义了,所以在页面就无需定义一个新的ckeditor了,注意看浏览器控制台,
*如果页面用ckeditor官方的方法定义一个ckeditor,就会出错,说重复定义一个ckeditor*/
app.directive('ckeditor', function() {
return {
require : '?ngModel',
link : function(scope, element, attrs, ngModel) {
var ckeditor = CKEDITOR.replace(element[0], {

});
if (!ngModel) {
return;
}
ckeditor.on('instanceReady', function() {
ckeditor.setData(ngModel.$viewValue);
});
ckeditor.on('pasteState', function() {
scope.$apply(function() {
ngModel.$setViewValue(ckeditor.getData());
});
});
ngModel.$render = function(value) {
ckeditor.setData(ngModel.$viewValue);
};
}
};
});

5、然后在页面写上,即可进行双向绑定!!(切记到这里就行了,不要画蛇添足在途写其他的,不然会报错的!)

<textarea ckeditor ng-model="topic.content" class="form-control" name="content"></textarea>

说明:如果没用到AngularJS,不需要进行ng-model的双向绑定的话 。就不用写Angular的directive指令就去掉第四和第五步,其他不变加上下面的即可

<textarea ckeditor ng-model="topic.content" class="form-control" name="content"></textarea>

<!--经自己的测试,这段js代码一定要放到此<textarea>标签之后-->

<script type="text/javascript">
CKEDITOR.replace('content'); //参数‘content’是textarea元素的name属性值,而非id属性值
</script>