Runnable CODE:
my code
我尝试动态地将contenteditable指令添加到< div>双击时的元素。
当我将contenteditable
指令放到< div>时在开始时,ng-model
仍然有用,但当我删除它并在ng-dblclick
回调中动态添加它时,ng-model
接缝不再起作用。
有点像this Question。
但是我无法想到在这里完成我的工作的角度友好的方式。 我该如何解决这个问题?
<div ng-app="customControl">
<form name="myForm" ng-controller="mainControl">
<!-- Dynamically adding contenteditable directive : doesn't work -->
<div name="myWidget" ng-model="userContent" ng-click="enableEdit($event)"
strip-br="true"
required>Change me!</div>
<hr>
<textarea ng-model="userContent"></textarea>
</form>
</div>
angular.module('customControl', []).
controller('mainControl', function($scope) {
$scope.enableEdit = function(e) {
$(e.target).attr('contenteditable', '');
}
})
.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('keyup change', function() {
scope.$apply(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);
}
}
};
});