故事从这里开始
// 正在调试angualar 1.4.3版本
// filter
App.filter('trustHtml', function($sce) {
return function(text) {
return $sce.trustAsHtml(text);
}
});
App.filter('replaceNtoBr', function() {
// 把\n换成br
return function(text) {
return text.replace(/\n|\\n/g, "<br/>")
}
});
App.filter('removeBr', function() {
// 这个是移除<br>的
return function(text) {
return text.replace(/<br\/>|<br>|\\n/g, "");
}
})
.directive("contenteditable", function() {
// 这个是让输入和value同步
return {
restrict: 'A', // 作为属性使用
require: '?ngModel', // 此指令所代替的函数
link: function(scope, element, attrs, ngModel) {
if (!ngModel) {
return;
}
ngModel.$render = function() {
element.html(ngModel.$viewValue || '');
};
element.on('blur keyup oninput change', function() {
readViewText();
});
function readViewText() {
var html = element.html();
if (attrs.stripBr && html === '<br>') {
html = '';
}
ngModel.$setViewValue(html);
}
}
};
});
html写法
<div ng-bind-html="htmlContent |replaceNtoBr|trustHtml "></div>
<!-- trustHtml是angular自己的函数,这个要放在最后一个要不就报错了 ,原因清楚明了-->
<span contenteditable="plaintext-only" ng-model="testvalue" ></span>
<!-- 这个是一个可以编写的文字的span标签。。。 -->
controller.js
App.controller('header', ["$scope",'$element',"$route",'$rootScope',function($scope, $element,$route,$rootScope) {
$scope.$route=$route;
// 这里是此次的重点
$scope.htmlContent="<h1>这是\n识别\n了html了\n非共和国非结构化</h1>";
$scope.abc = "点击的文字";
$scope.ccc=false;
$scope.toggle=function(){
$scope.ccc=!$scope.ccc;
}
}]);
重点讲下
contenteditable="plaintext-only"
是HTML的属性,可以让编辑区域只能键入纯文本。非谷歌浏览器不兼容,所以不常见,但是也说明孤陋寡闻了。
css也有可以让元素可以编辑的属性
user-modify: read-write-plaintext-only
只有webkit内核浏览器才支持read-write-plaintext-only
这个值,因此,我们的使用其实是:
-webkit-user-modify: read-write-plaintext-only
此处css观点学习自https://www.zhangxinxu.com/wordpress/2016/01/contenteditable-plaintext-only/