我需要提供用户功能,这样他就可以在textarea中添加一些占位符,比如电子邮件模板。我设法找到插入位置并插入新创建的节点,但即使我使用$compile
ng-click也没有触发doStuff()
函数。
angular
.module('app.shared')
.directive('placeholderInput', placeholderInput);
function placeholderInput($compile) {
return {
restrict: 'E',
scope: {
content: '=',
inputClass: '=',
variables: '='
},
templateUrl: 'app/js/shared/directives/placeholderInput.html',
link: function(scope, elem) {
scope.popoverOpen = false;
var textArea = elem[0].querySelector('.placeholder-input-textarea');
scope.insertPlaceholder = function(variable) {
textArea.focus();
var range = getRange(textArea);
var newNode = document.createElement('span');
newNode.setAttribute('contenteditable', false);
newNode.setAttribute('class', 'label label-primary');
newNode.setAttribute('ng-click', 'doStuff()');
newNode.appendChild(document.createTextNode(variable.label));
$compile(newNode)(scope);
range.insertNode(newNode);
// var span = angular.element($compile('<span class="label label-primary" contenteditable="false" ng-click="doStuff()">span</span>')(scope));
scope.content = angular.element(textArea).html();
scope.popoverOpen = false;
}
scope.doStuff = function() {
console.info(123);
}
var getRange = function(element) {
var range;
var caretOffset = 0;
var doc = element.ownerDocument || element.document;
var win = doc.defaultView || doc.parentWindow;
var sel;
if (typeof win.getSelection != "undefined") {
sel = win.getSelection();
if (sel.rangeCount > 0) {
range = win.getSelection().getRangeAt(0);
}
} else if ( (sel = doc.selection) && sel.type != "Control") {
range = doc.body.createTextRange();
}
return range;
};
}
};
}
视图:
<div>
<div ng-model="content" class="placeholder-input-textarea {{inputClass}}" contenteditable="true"></div>
<button uib-popover-template="'placeholderInputVariables.html'" popover-placement="right" popover-is-open="popoverOpen" type="button">+</button>
</div>
<script type="text/ng-template" id="placeholderInputVariables.html">
<div class="list-group">
<button ng-repeat="variable in variables" type="button" ng-click="insertPlaceholder(variable)" class="list-group-item">{{variable.label}}</button>
</div>
</script>
请帮忙。也许你会得到一些其他的想法。
答案 0 :(得分:0)
也许只是改变这两行的顺序:
这
$compile(newNode)(scope);
range.insertNode(newNode);
到
range.insertNode(newNode);
$compile(newNode)(scope);