Enhance Summernote functionality by creating a custom button that can access and utilize

Using summernote in my Angular project, I am looking to create a custom button that can pass a list as a parameter.

I want to have something like 'testBtn': this.customButton(context, listHit) in my custom button function, but I am unsure how to achieve this due to the current function structure. Any assistance on this matter would be greatly appreciated. Thank you!

This is the code snippet for my custom button:

  customButton(context) {    
    
    var listHit = ['One', 'Two', 'Tree'];
    
    const ui = ($ as any).summernote.ui;
    var i;
    var listHitHtml = "";
    for (i = 0; i < listHit.length; i++) {
      listHitHtml += "<li>" + listHit[i] + "</li>";
    }


    var button = ui.buttonGroup([
      ui.button({
        className: 'dropdown-toggle',
        contents: '<i class="fa fa-comments"/><span class="caret"></span>',
        tooltip: '@erp_colombia.Lang.Resource.conAvailableComments',
        data: {
          toggle: 'dropdown'
        }
      }),
      ui.dropdown({
        className: 'drop-default summernote-list',
        contents: "<div id=\"container-comentario\"><div id=\"dialog\" title=\"Comentarios\" ><h1 class=\"header-comentario\">" + 'Comment' + "</h1><ul id=\"liste-comentarios\"><ul>" + listHitHtml + "</ul></div></div>",
        callback: function ($dropdown) {
          $dropdown.find('li').each(function () {
            $(this).click(function () {
              context.invoke("editor.insertText", $(this).html() + "\n");
            });
          });
        }
      })
    ]);

    return button.render();   // returning button as a jQuery object
  }

This is the configuration for pdfmaker:

  this.config = {
    placeholder: placeholder,
    shortcuts: false,
    disableDragAndDrop: true,
    hint: {
      mentions: this.quoteCommentsForSummerNote,
      match: /\b(\w{1,})$/,
      search: function (keyword, callback) {
        callback($.grep(this.mentions, function (item: any) {
          return item.indexOf(keyword) == 0;
        }));
      },
      content: function (item) {
        return item;
      }
    },
    height: 200,
    toolbar: [
      ['myotherbutton', ['testBtn']],
    ],
    buttons: {
      'testBtn': this.customButton
    }
  }

Here is the HTML on my Angular component:

In this demo, I have created an example of a list retrieved from a service which should be passed to the customButton:

  listStringFromDbService = ['one', 'two', 'three'];

https://stackblitz.com/edit/angular-summernote-demo-gdvvbn?file=src%2Fapp%2Fapp.component.ts

Answer ā„–1

After some experimentation, I have come to a solution.

To enhance flexibility, consider modifying your button declaration into a function that produces a button function. This way, you can pass data to it prior to constructing the function bound to testBtn.

Revise the function declaration (either through expression or declaration as per your preference)

function dynamicButtonGenerator(arr) {
  return function (context) {
    const ui = $.summernote.ui;
    const button = ui.button({
      contents: '<i class="note-icon-magic"></i> Hello',
      tooltip: 'Custom button',
      container: '.note-editor',
      className: 'note-btn',
      click: function () {
        context.invoke('editor.insertText', 'Hello from test btn!!! ' + arr);
      },
    });
    return button.render();
  };
};

Subsequently, when configuring the UI, generate the button function accordingly:

buttons: {
      testBtn: dynamicButtonGenerator(this.listStringFromDbService),
    },

For a live demonstration, check out this updated stackblitz example.

Answer ā„–2

I have made some modifications to MPawlak's answer by adding a dropdown feature for selecting items to add. Additionally, I successfully passed parameters to the custom button as well. Huge thanks to MPawlak for the initial inspiration!

Explore the changes here

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

Fixing the Jquery Clone Bug

Recently, I came across a jQuery clone plugin that is designed to fix the values of cloned textarea and select elements. This code snippet showcases how it works: (function (original) { jQuery.fn.clone = function () { var result = ori ...

Resetting JavaScript Input based on certain conditions

I have been attempting to reset the input fields for a login when the loginDiv display is set to none, but unfortunately it does not seem to be working as expected. My goal is for the input fields to reset whenever the login button is clicked and the logi ...

Tips on utilizing useStyle with ReactJS Material UI?

Is there a way to utilize a custom CSS file in the useStyle function of Material UI? I have created a separate useStyle file and would like to incorporate its styles. Can someone explain how this can be accomplished? input[type="checkbox"], inp ...

Is it possible to create Firebase real-time database triggers in files other than index.js?

Is it possible to split a large index.js file into multiple files in order to better organize the code? Specifically, can Firebase triggers be written in separate JavaScript files? If so, could you please provide guidance on how to do this properly? child. ...

What is the best approach to tackle this design?

As a newcomer to React, I'm facing challenges in positioning components. The layout I envision is consistent across all pages, with certain elements remaining the same. Should I utilize a grid system for this design? How should I approach achieving th ...

Setting the isLogged variable for other components in Angular 2 can be accomplished by using a shared

I am using a principalService to retrieve the current authenticated user from the backend server, and authService.ts includes a local variable 'isLogged:boolean'. Goal: I need to access the value of 'isLogged' from authService in Navba ...

Refreshing a specific div within an HTML page

I am facing an issue with the navigation on my website. Currently, I have a div on the left side of the page containing a nav bar. However, when a user clicks a link in the nav bar, only the content on the right side of the page changes. Is there a way t ...

Looking to create a format for displaying short comic strips in a grid pattern

I am struggling to create an image grid for my small comics. I want to have 2 columns and 3 rows, but all the divs end up in the same place. I tried using display: flex, but it didn't work as expected. Additionally, I want the grid to be responsive, b ...

Experimenting with a TypeScript function containing a subscription operation

Currently, I am experimenting with Jasmine/Karma while working on an Angular 4 project. The issue I'm facing involves testing a function that seems to have trouble setting the 'name' property: https://i.stack.imgur.com/3q49i.jpg The assign ...

Transforming a JavaScript Date object to a Java LocalDateTime

In my current project, I am facing a challenge while attempting to pass UTC time from a JavaScript front end to a Java backend. My initial approach involved utilizing the Date.toISOString() method and sending the generated object to the Java backend. Howev ...

Having difficulty inputting password for telnet login using Node.js

When I use telnet from the Windows command line, everything works smoothly: > telnet telehack.com (... wait until a '.' appears) . login username? example password? (examplepass) * * * * * * * Logged... (...) @ (This is the prompt when you ...

Is there a way to present both Javascript and templates from parallel directories using express?

QUERY: Is there a way to modify the server.js file so that the three.js script in index.html does not display an error message like Cannot GET /node_modules/three/three.js? Code Snippet: index.html <!DOCTYPE html> <html lang="en"> <head&g ...

`The resurgence of CERT_FindUserCertByUsage function in JavaScript`

I am currently grappling with unraveling the connection between C++ dlls and JavaScript. There is a snippet of js code that reads: cert = CERT_FindUserCertByUsage(certDB, certName.nickname,certUsageEmailSigner, true, null); where the variable cert is ini ...

What are the effects of calling callback(false) and callback(true)?

I'm currently diving into a nodejs chat project, and Iā€™m a bit confused about the outcome when callback(false) and callback(true) are triggered in this context... io.sockets.on('connection', function(socket){ socket.on('new user& ...

Guide on showcasing an alert notification when the data is already existing within an array through javascript

Need help with displaying an alert message in JavaScript for duplicate values in an array? var names = []; var nameInput = document.getElementById("txt1"); var messageBox = document.getElementById("display"); function insert() { names. ...

Having trouble invoking an established route within a different route in an Express JS project

While working with an Express JS application connected to a mySQL database, I encountered an issue when trying to fetch data from a pre-defined route/query: // customers.model.js CUSTOMERS.getAll = (result) => { let query = "SELECT * FROM custo ...

Making an API request at regular intervals of x seconds

I am currently working on an Angular chat application where I need to fetch new messages at regular intervals. The time intervals for fetching new messages are as follows: 1. Every 5 seconds 2. Every 10 seconds 3. Every 20 seconds (if there are new message ...

Executing a function on a dropdown menu in AngularJS

Currently facing an intriguing scenario that is causing me some confusion. This question is specifically for those well-versed in Angular UI Grid, but all responses are welcome. The situation revolves around a UI Grid with a dropdown functionality impleme ...

Sending information in Json format back to an Ajax request

I have a method in the Model-View-Controller (MVC) framework where I submit data and expect to receive some processed data back. The MVC method I am posting to returns JSON data. [HttpPost] public JsonResult GetCalculateAmortizationSchedule() { var da ...

Fade out the notification div using jQuery in MVC4

I'm a beginner in the world of JavaScript and JQuery and I could really use some assistance with resolving a simple issue that I've encountered. As part of my application's functionality, I am dynamically loading the following div based on ...