Angular instructions

I am fairly new to working with Angular. Currently, I am using Angular 1.6 and I have been tasked with making some modifications to an existing application.

After doing some research, I discovered that the previous developer had used in order to create a textarea with text options and a preview feature. Now, my job is to override the preview button so that it calls our API with the inserted text and receives a result in return. In the documentation of the markdown tool I found, I came across the following code:

onPreview: function(e) { var previewContent

if (e.isDirty()) {
  var originalContent = e.getContent()

  previewContent = "Prepended text here..."
         + "\n"
         + originalContent
         + "\n"
         +"Apended text here..."
} else {
  previewContent = "Default content"
}

return previewContent

},

Thus, I began the process of overriding it:

app.directive("markdowntextarea", ['$http', function ($http) {
    return {
        link: function (el_scope, element, attr) {
            var previewContent = "preview";
            element.markdown(
                {
                    autofocus: false,
                    savable: false,

                    onPreview: function (e) {
                        console.log('1');
                        if (e.isDirty()) {
                            console.log('2!!')
                            var originalContent = e.getContent();
                            $http({
                                url: '/api/markdown/',
                                data: {"body": originalContent, "actual_format": "md", "desire_format": "html"},
                                method: 'POST'
                            }).then(function successCallback(response) {
                                console.log(response.data.content);
                                previewContent = response.data.content;
                            });
                        }else{
                            console.log('3')
                            previewContent = "";
                        }
                        previewContent = 'test';
                       return previewContent;
                    },
                });
        }
    }
}]);

Despite my efforts, I am unable to identify the error I made. The previewContent variable always returns "preview". The API seems to be working fine and the response.data.content is correct as well.

At this point, I am unsure of what steps to take next.

Answer №1

In order to handle an asynchronous function and retrieve its value, a solution is needed. For instance, in AngularJS, promises can be used to address this issue. Promises are described as "A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing".

However, it seems that the markdown component used in the code does not support promises based on the source. The onPreview method requires a string to be returned, making it impossible to directly incorporate AJAX requests inside onPreview.

If the bootstrap-markdown were to support promises, a potential approach could be as follows:

app.directive("markdowntextarea", ['$http', '$q', function ($http, $q) { // inject $q
...
onPreview: function (e) {
    console.log('im here!!');
    var deferred = $q.defer();
    if (e.isDirty()) {
        var originalContent = e.getContent();
        $http({
            url: '/api/markdown/',
            data: {"body": originalContent, "code": "a"},
            method: 'POST'
        }).then(function successCallback(response) {
            console.log("successCallback", response.data.content);
            deferred.resolve(response.data.content);
        }, function errorCallback(response) {
            console.log("errorCallback");
            deferred.reject("error");
        });
    } else {
        deferred.resolve("");
    }
    return deferred.promise;
},
...

A demonstration of this concept can be found in this JSFiddle, which is an update of Dave Kerr's AngularJS Promises - The Definitive Guide Part 2 - JSFiddle for AngularJS 1.6.

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

"Enhancing User Experience with AngularJS by Dynamically Modifying and Refresh

I'm currently attempting to dynamically add HTML elements using JavaScript with a directive: document.getElementsByClassName("day-grid")[0].innerHTML = "<div ng-uc-day-event></div>"; or var ele = document.createElement("div"); ele.setAttr ...

"Integrating Vuetify into a single-spa Vue application: Step-by-step

vue 2.6.14 vuetify 2.6.9 What is the process for integrating vuetify into a vue application? I am attempting to import my project into another project as a microfrontend application, but encountering issues. Here are the steps I followed: Create-single- ...

Unable to execute findOneAndUpdate as a function

I've been researching all morning and testing different solutions, but I'm still unable to resolve this issue. Every time I run the code below, I receive the error "TypeError: req.user.findOneAndUpdate is not a function": req.user.findOneAndUpd ...

Unable to receive acknowledgment from child component within Redux

I am trying to retrieve props from Redux within a child component, but for some reason, {this.props} is showing up as an empty object. While I am successfully using react-redux connect to access the props in the parent component and pass them down to the ...

The amazing magnific popup boasts a pair of close buttons

I recently started working on integrating a front-end HTML theme with a back-end Laravel app. Oddly enough, I noticed that the popup modal is displaying two close x buttons instead of just one. Despite my efforts, I have been unable to pinpoint what exactl ...

remove a row from a table within a Firestore database

I'm currently working on implementing a button to delete a specific row in my table from the Firebase database, but I'm uncertain about how to achieve this using a button function. My code is written in JavaScript and utilizes Firestore. Below i ...

Tips for storing dynamically added row data from an HTML table to a (csv/txt) file using C#

I am dynamically adding new rows to a table named "newDataTable" using the JavaScript function below: function addRow() { //add a row to the rows collection and get a reference to the newly added row var table = document.getElemen ...

Automatically close the multiselect dropdown when the user interacts outside of it (varied scenario)

For those interested, check out this jsfiddle link: http://jsfiddle.net/jaredwilli/vUSPu/ This specific code snippet focuses on creating a multi-select dropdown feature. When a user chooses options from the dropdown and then clicks outside of the menu are ...

Unable to access marker windows using markers tag on angular-google-maps

Objective Display various random markers on a map and open an information window upon clicking on them. I attempted to implement this using an example from the API page (markers) and included the necessary code for the window and click handler method. Unfo ...

Regular expressions work when used on the internet, but they don't seem to

I'm encountering a peculiar situation with a regular expression. Here is the expression in question: const csrfRegex = /"csrf_token": "((\\"|[^"])*)"/ig; The main objective is to extract the CSRF token from a Javascript object on a website ...

How can NodeJS Websocket (ws) facilitate communication between various clients?

In my project, I have a scenario where client1 needs to share information with client2 and the latter should receive an alert upon receiving it. To achieve this, I am utilizing Websocket "ws" with NodeJS. The web page for client1 receives a response via A ...

The React-native application initialized using npx create-react-app encountered an error and could not launch

Hello there, A couple of months back, I developed an app using create-react-app. However, when I tried to run it with npm start, I encountered the following error message: react-scripts start It seems like there's an issue with the project depende ...

Using the EJS if-else statement to iterate through an array of items

I am working on rendering API data using Express (REST) and EJS (template engine) based on the value of the "status" field. If any item in the array has a status other than "CLOSED," it should be displayed, but if all items have the status set to "CLOSED," ...

Create a navigation link in Vue-bootstrap that directs to an 'external program'

After deciding to use vue-bootstrap instead of just bootstrap for its additional features like tabs, I made the choice to rewrite the navigation using it as well. However, I encountered an issue where the links in the navigation menu are pointing to the co ...

"Utilize Ajax to load PHP content and dynamically refresh a specific div

I have implemented an image uploading system, but now I want to incorporate a feature that allows users to rotate the uploaded images using Ajax. The challenge I'm facing is that if the session variable is lost during a full page update, I need to ens ...

Determining the duration since generating a unique objectid in mongodb

I am currently developing an application that offers users the option to reset their passwords. The process is quite straightforward - after entering his email address, the user will receive a link containing the new objectid number. For example: /reset- ...

Preventing special characters, numbers, and spaces from being used as the first character in a word in HTML with regular expressions

Is there a way to restrict users from inputting special characters, numbers, and spaces only in the first place of a word using regex in HTML? <label><span>Current Carrier</span></label> <input name='Current Carrier' t ...

Tips for concealing a dynamic table element in Angular 9

I have dynamically generated columns and rows in a table. Here is my HTML for the table component: <table id="tabella" class="table table-striped table-hover"> <thead class="thead-dark"> <tr> <th *ngFor="let header of _ob ...

Sorting a Vue.js checkbox in the header of a data table

I'm currently facing an issue with a project I'm handling. The data in question is stored in a v data table, where the header data is retrieved from an external API. Inside this table, there are checkboxes for users to select specific businesses ...

Is there a way to incorporate a third button into an editable field using AngularJS?

I'm curious about customizing the AngularJS editable framework. I noticed that when using an editable element, two buttons appear - a save button and a cancel button. However, I'd like to add a third button with a minus symbol to delete the text ...