What is the best way to enable one directive to be utilized across multiple inputs in Angular Material?

Here is a code snippet that I am working with:

<md-input-container class="new-paragraph addon-menu">
    <label>Post text</label>
    <textarea ng-model="user.post" rows="3"></textarea>
</md-input-container>
<md-menu>
    <md-button aria-label="" class="md-icon-button" ng-click="$mdOpenMenu($event)">
        <i class="fa fa-plus-square-o mobile-menu-ic light-gray-text font-size-extra-large"></i>
    </md-button>
    <md-menu-content>
        <md-menu-item ng-repeat="templateVariable in templateVariables">
            <md-button ng-click="injectVariableAtCursor(templateVariable);">{{templateVariable}}</md-button>
        </md-menu-item>                                                             
    </md-menu-content>
</md-menu>

I would like to add predefined text (at cursor position) to the user.post model when a user clicks on a specific item within the <md-menu-content>.

I understand that using directives with isolated scope could be beneficial, but I am unsure how to go about implementing this since the input and buttons are not directly related under a single ngModel.

Any ideas or suggestions?

Answer №1

You can achieve the desired outcome without using a directive.

Based on my understanding of your issue, the following code snippet should suffice:

controller :

$scope.injectVariableAtCursor = function(templateVariable) {
 $scope.user.post = templateVariable;
};

Here's a demonstration of the functionality you are looking for :

var myController = function($scope) {
  var target = null;
  
  $scope.user = { post: "first" };
  
  $scope.handleFocus = function(event) {
    target = event.target;
  };
  
  $scope.handleClick = function(text) {
    var start, end, actual = $scope.user.post;
    
    if(target) {
      start = target.selectionStart;
      end = target.selectionEnd;
    }else{
      start = end = $scope.user.post.length;
    }
    
    
    $scope.user.post = actual.substr(0,start) + text + actual.substr(end, actual.length);
  };
};

angular.module('controller', [])
  .controller('myController', myController);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="controller">
  <div ng-controller="myController">
    <textarea ng-model="user.post" ng-focus="handleFocus($event)"></textarea>
    
    <button ng-click="handleClick('bla')">add bla</button>
  </div>
  
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to determine if an application has been installed on an Android device while browsing a website?

Let's set the scene: I've got a website that needs to use JavaScript to determine whether my app is already installed on the android device it's currently being used on. If the app is installed, the page will display a link (with a custom ...

What is the best way to generate an empty object that mimics the structure of an object within an array of objects in AngularJS

I am facing a scenario where I have an array of objects structured like this: $scope.users = [ { ID: "1", Name: "Hege", Username: "Pege", Password: "hp", }, { ID: "2", Name: "Peter", User ...

A guide to updating a particular row and sending parameters with jQuery and AJAX

I am utilizing a JSON response to dynamically display table content. Here is the code I am using to display row values: var rows = ''; for(var i=0; i<response.response.length; i++) { rows += '<tr><td class="country">&ap ...

Having issues with the jQuery .css function?

I need help with hiding and showing tabs on my webpage based on a successful login. I have tried various methods, such as setting the tab to be hidden by default in the HTML code and then using JavaScript to display it upon login. However, none of these me ...

Exploring Object Elements using For Loop

After trying numerous methods, I am still puzzled by this issue. I have a feeling that the solution is going to be something very simple, but nevertheless, I need to ask for help. This is the function I'm dealing with: Module.load = function(a) { ...

The page loads successfully at first, but upon refreshing, a 404 error occurs when using Zeit, Nextjs, and now

After recently updating from now v1 to v2, I encountered an issue where my pages would return a 404 error when reloading after pushing to production using now --prod. While everything worked fine locally with now dev, the routing seemed to be causing confu ...

Conceal the div on larger screens and display it on mobile devices

I have a fixed navigation bar at the top of my website. By default, it is always visible on all pages, but I want to hide it on desktop screens and display it only on mobile devices. Here is what I have implemented: @media (min-width: 992px) { #sp-he ...

How can we display or conceal text indicating the age of a patient based on the value returned from selectedPatient.age in a React application?

Hello, I am looking to dynamically display the age in years on the screen based on the value retrieved from selectedPatient.age, toggling between visible and hidden states. import React, { useContext } from 'react'; import { useHistory } from &ap ...

Executing a function when a webpage loads in Javascript

I have created a responsive website using Twitter Bootstrap. On my site, I have a video displayed in a modal that automatically plays when a button is clicked. Instead of triggering the function with a button click, I want the function to be called when ...

Optimal Placement of jQuery Event Handlers in React/Redux Components with Asynchronous Data Loading

After reviewing the ReactJS documentation, it's clear that the most suitable lifecycle method for handling redux action calls is componentDidMount. However, I'm facing a challenge when it comes to incorporating jQuery operations within this parti ...

Unable to Retrieve Modified Content with $().text();

In the process of developing an app, I am encountering a challenge where I need to transfer user input to another element after processing it. However, I am facing an issue with accessing the updated value of the <textarea> using .text(), as it only ...

What is the process for creating separate files for modal controllers?

I have an Angular application with multiple modals, and I am using AngularUI to handle the modal directive. http://angular-ui.github.io/bootstrap/ Currently, my main controllers are all located in the app.js file as routes. $routeProvider.when '/da ...

"Implementing a 2D graphical user interface on a three.js

Struggling to create a 2D graphical user interface on the renderer. The challenge lies in positioning the 2D GUI dynamically based on the width of an element drawn in threejs (the element has a width of X using threejs units, and the menu needs to be posit ...

Updating AngularJS views based on window resizing

I've been working on an Angularjs application and everything is running smoothly, but I'm facing challenges when it comes to implementing a mobile version of the site. Simply using responsive styles won't cut it; I need to use different view ...

Encountering an error message stating "Please enable JavaScript to run this application" when making React API calls after deploying a ReactJs app on the Firebase server

I'm currently working on a React JS app that calls various APIs. The backend of this application is a NodeJs server deployed in GCloud. While everything runs smoothly when I test the React app locally, I encountered an issue after deploying it to Fir ...

Pause file uploads, display modal popup, then resume uploading

Is there a way to pause file uploading in order to display file requirements before proceeding? For example, when a user clicks on "upload file", I would like to show them a modal window with details about the file they need to upload. Once they click ok, ...

When ran automatically as a cron job, the JavaScript script fails to establish a connection with MongoDB

As I connect to mongodb (on a Ubuntu machine) from a js script, everything runs smoothly when I execute the command from the command line (node <name of the script>). However, when I try executing the same command from cron, the connection times out: ...

Save the function as a local variable and preserve the reference to the current object

In the prototype of my Car object, I have a function that looks like this: Car.prototype.drive = function() { this.currentSpeed = this.speed; } I find myself needing to call this drive function frequently within another function of the Car prototype. ...

The onclick attribute on a button in HTML is not functioning properly following the inclusion of an Ajax load

I am facing an issue with a button that is being dynamically loaded from PHP code using Ajax. The button has an onclick attribute that calls a function named viewImage. The Ajax request is triggered every 5 seconds inside the loadImages function. Snippet ...

The behavior of Mozilla in handling JQuery attr() function may result in variations in design elements such as font-family or font-size

I'm currently working on the login form. Below is my view in CodeIgnitor: <div id="login-form"> <?php echo heading('Login', 2); echo form_open('login/login_user'); echo form_input('email', set_value ...