我有一个可编辑的输入字段,当我单击它时,它必须在框中将背景颜色设置为白色。请帮助我。
我在这里分享我的代码:
HTML
<div id="section{{section.index}}">
<h2 class="title" contenteditable="true" ng-model="section.title"
onclick="document.execCommand('selectAll',false,null)"
ng-keydown="disable_enter($event)"
ng-change="check_section_title($index)"
maxlength="40">
</h2>
</div>
我就是这样
最佳答案
contenteditable
元素的自定义指令
使 contenteditable
元素与 ng-model directive 一起使用
和 ngModelController :
<div contenteditable
name="myWidget" ng-model="userContent"
strip-br="true"
required>Change me!
</div>
创建 custom directive :
app.directive('contenteditable', ['$sce', function($sce) {
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($sce.getTrustedHtml(ngModel.$viewValue || ''));
};
// Listen for change events to enable binding
element.on('blur keyup change', function() {
scope.$evalAsync(read);
});
read(); // initialize
// Write data to the model
function read() {
var html = element.html();
// When we clear the content editable the browser leaves a <br> behind
// If strip-br attribute is provided then we strip this out
if (attrs.stripBr && html === '<br>') {
html = '';
}
ngModel.$setViewValue(html);
}
}
};
}]);
The DEMO
angular.module('app', ['ngSanitize'])
.directive('contenteditable', ['$sce', function($sce) {
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($sce.getTrustedHtml(ngModel.$viewValue || ''));
};
// Listen for change events to enable binding
element.on('blur keyup change', function() {
scope.$evalAsync(read);
});
read(); // initialize
// Write data to the model
function read() {
var html = element.html();
// When we clear the content editable the browser leaves a <br> behind
// If strip-br attribute is provided then we strip this out
if (attrs.stripBr && html === '<br>') {
html = '';
}
ngModel.$setViewValue(html);
}
}
};
}])
<script src="//unpkg.com/angular/angular.js"></script>
<script src="//unpkg.com/angular-sanitize/angular-sanitize.js"></script>
<body ng-app="app">
<form name="myForm">
<p>Click on below div to edit</p>
<div contenteditable
name="myWidget" ng-model="userContent"
strip-br="true"
required>Change me!</div>
<span ng-show="myForm.myWidget.$error.required">Required!</span>
<hr>
<textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
</form>
</body>
有关详细信息,请参阅AngularJS ngModelController API Reference - Custom Control Example
关于javascript - contenteditable - 如何使用 angularjs 仅使标题位于 block 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45726879/