如果您在内容可编辑的情况下按Enter键,我不希望发生任何事情:
这是我在指令中尝试的内容:
element.on('blur keyup change', function (e) {
if(e.which == '13')
e.preventDefault();
以下是整个指令:
.directive('contenteditable', function () {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function (scope, element, attrs, ngModel) {
if (!ngModel) return; // do nothing if no ng-model
// Specify how UI should be updated
ngModel.$render = function () {
element.html(ngModel.$viewValue || '');
};
// Listen for change events to enable binding
element.on('blur keyup change', function (e) {
if(e.which == '13')
e.preventDefault();
scope.$apply(readViewText);
});
// No need to initialize, AngularJS will initialize the text based on ng-model attribute
// Write data to the model
function readViewText() {
var html = element.html();
//cleaning out html for saving data.
console.log(html);
html = html.replace(/(<([^>]+)>)/ig,"");
/* .replace(/<div><br\s*[\/]?><\/div>/gi,'')
.replace(/<div>/gi,'\n')
.replace(/<\/div>/gi,'')
.replace(/<br\s*[\/]?>/gi,'');*/
console.log(html)
ngModel.$setViewValue(html);
}
}
};
});
答案 0 :(得分:4)
我最终这样做了:
element.on('keydown', function (event){
if(event.which == '13'){
window.event.cancelBubble = true;
event.returnValue = false;
insertTextAtCursor('\n');
}
});
答案 1 :(得分:0)
试试这个,希望它有效,否则需要玩代码
ngModel.$parsers.unshift(function (inputValue) {
var noEnter = inputValue.replace(/[\n]/g, "");
ngModel.$viewValue = noEnter;
ngModel.$render();
return noEnter;
});
答案 2 :(得分:0)
这似乎足以实现这一目标:
element.on('keydown', function(e) {
if (e.keyCode == 13) {
return false;
}
});
要在keydown处抓住事件,以便以后的密钥永远不会触发。