Directive for injecting a string at the cursor position

I was assigned to work on a task where if a user clicks on a specified html element and clicks an add button, then a dropdown’s selected value will appear where the cursor’s last position was.

This was achieved using the Range API

I created a directive which is applied on a html element of my choice, a function in the controller that broadcasts the event that the directive is listening to which injects the passed in string value.
I also pass in a CSS ID so as to make sure that we are only injecting inside the clicked on HTML element.

First, here’s the directive:
app.directive('injectPlaceholders', ['$rootScope', function ($rootScope) {
return {
link: function (scope, element, attrs) {
scope.$on('injectSelectedPlaceholder', function (e, placeHolderInfo) {
if (window.getSelection) {
var selection = window.getSelection();

if (selection.getRangeAt && selection.rangeCount) {
var selectionRange = selection.getRangeAt(0);

var userClickedInsideSpecifiedElement = $(selectionRange.commonAncestorContainer).parents(placeHolderInfo.text_area_id).length === 1;

if (userClickedInsideSpecifiedElement ) {

Here is the controller function that is bound to the button’s ng-click event that does the broadcasting.
$scope.injectSelectedPlaceholder = function () {
var placeHolderInfo = {
place_holder: $scope.selectedPlaceHolder,
text_area_id: "#UIMessageTextArea"

$rootScope.$broadcast('injectSelectedPlaceholder', placeHolderInfo);




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s