Recently, I am using angular to make a WYSIWYG editor. When I customize the $render method of ngModel, a problem occurs. The code is as follows:
html part:
<p ng-controller="EditController">
<p contenteditable="true" edit-box ng-model="vm.content" style="width: 300px; height: 100px;border: 1px solid dodgerblue;"></p>
<p ng-bind-html="vm.content|trustAsHtml"></p>
</p>
angular part:
angular.module('myApp',[])
.controller('EditController',function($scope){
$scope.vm={
content:''
};
})
.filter('trustAsHtml',function($sce){
return function(content){
return $sce.trustAsHtml(content);
}
})
.directive('editBox',function(){
return {
restrict:'EA',
require:'ngModel',
link:function(scope,element,attr,ngModelCtrl){
if(!ngModelCtrl)return;
//覆盖默认的$render方法
ngModelCtrl.$render=function(){
element.html(ngModelCtrl.$viewValue);
};
//向formatters流水线增加一个格式化方法
ngModelCtrl.$formatters.unshift(function(value){
console.log(value);
return value;
});
//绑定输入事件监听,当输入时,改变ngModel的值
element.bind('input',function(){
scope.$apply(function(){
ngModelCtrl.$setViewValue(element.html());
});
});
}
}
});
According to the tutorial, when the value of viewValue changes, ngModelCtrl.$render will be called, including a series of pipelines such as formatters and parsers. I also wrote it according to the tutorial, but render and formatters are only called once during the initialization of the command, and then they are not called when typing. Do I need to call render manually? Please enlighten me.
Are you sure
javascript
里有一个事件叫input
?按你的注释来看,你应该监听keyup
,keydown
,change
this kind of incident