contenteditable div
self editbale div with emoticons
by nunofaria11
HTML
<div ng-app="ceApp" ng-controller="ceController">
<div>
<p>
<h3>Editable div</h3>
<!--div id="ce" contenteditable="true" ng-model="textModel"></div-->
<div id="ce" contenteditable="true" ng-model="anotherModel" ng-bind-html="anotherModel | emoticons"></div>
</p>
<p>
<h3>Filter:</h3> <span ng-bind-html="textModel | emoticons"></span>
</div>
<div>
<hr>
<h3>Supported symbols</h3>
<table>
<tr>
<th>Symbol</th>
<th>Image</th>
</tr>
<tr ng-repeat="(symbol, src) in emoticonSymbols">
<td ng-bind="symbol"></td>
<td>
<img ng-src="{{src}}" />
</td>
</tr>
</table>
</div>
</div>
CSS
#ce {
background-color: lightblue;
}
img {
width: 25px;
}
JavaScript
var ceApp = angular.module('ceApp', []);
ceApp.controller('ceController', ['$scope', 'emoticonsService', function ($scope, emoticonsService) {
$scope.textModel = "this is just a test for emoticons filter :)";
$scope.emoticonSymbols = emoticonsService.get();
$scope.anotherModel = "this is another text :)";
$scope.$watch('anotherModel', function () {
console.log('change');
});
}]);
ceApp.filter('emoticons', ['$sce', 'emoticonsService', function ($sce, emoticonsService) {
var _symbols = emoticonsService.get();
var imgTemplate = '<img src="{image-src}"></img>';
var escape = function (text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};
var escapedSymbols = [];
for (var s in _symbols) {
escapedSymbols.push(escape(s));
}
var regexp = new RegExp('(' + escapedSymbols.join('|') + ')', 'g');
var _replaceSymbols = function (val) {
if (val) {
var html = val.replace(regexp, function (symbol) {
console.log('replacing: ', symbol);
var base64Data = _symbols[symbol];
return imgTemplate.replace('{image-src}', base64Data);
});
return $sce.trustAsHtml(html);
}
return '';
};
return _replaceSymbols;
}]);
ceApp.directive("contenteditable", ['$filter', function ($filter) {
return {
restrict: "A",
require: "ngModel",
link: function (scope, element, attrs, ngModel) {
function read() {
//var value = element.html();
var value = $filter('emoticons')(element.html());
ngModel.$setViewValue(value.toString());
}
ngModel.$render = function () {
element.html(ngModel.$viewValue || "");
};
element.bind("blur keyup change", function () {
...