Update the promise status to reflect any changes

While attempting to modify the button text based on the promise status, I created a custom directive for this purpose.

Below is the code snippet for my custom directive:

.directive('myDir',function(){
          return {
            scope: {
              myDir: '&',
              afterValue: '@',
              beforeValue:'@',
              ngDisable:'=',
            },
            link: function ($scope, element, attrs) {
              element[0].innerHTML=$scope.beforeValue;
              element.bind('click',function(){
                console.log(element);

                element[0].innerHTML=$scope.afterValue;
                element[0].className+="disabled";
                element[0].disabled='true'
                $scope.myDir();
                //success i would like to change the status here
              })
            }
          }

        })

Here is the corresponding controller code:

.controller('myCtrl',[function(){
          var vm = this;
          console.log("MYCTRL");
          vm.fun= function(){
            //promise running here
          }
        }])

Furthermore, you can access the working example via this Plnkr link : https://plnkr.co/edit/Qj9GG2?p=templates/

I am currently facing difficulty in capturing the success of the promise in the directive.

Answer №1

If you want to retrieve the result of a promise, you can utilize the .then method. In this demonstration, I establish a promise that resolves after 2 seconds. Once resolved, the directive will modify the text displayed on the button.

Creating a promise using $q is showcased below:

  vm.fun= function(){
    // Promise execution here
    return $http.get('www.foo.org');
  }

angular
        .module('myApp',[])
        .directive('myDir',function(){
          return {
            scope: {
              myDir: '&',
              afterValue: '@',
              beforeValue:'@',
              ngDisable:'=',
            },
            link: function ($scope, element, attrs) {
              element[0].innerHTML=$scope.beforeValue;
              element.bind('click',function(){                  
                element[0].innerHTML=$scope.afterValue;
                element[0].className+="disabled";
                element[0].disabled='true'
                $scope.myDir().then(function(){
                  // On success, change status here  
                  // Update status here...
                  console.log('Callback from promise. Everything is fine.');
                  
                  element[0].disabled=false;
                  element[0].innerHTML = $scope.beforeValue;
                }, function(){
                    // Error handling for promise failure
                    console.log('Callback from promise. Something went wrong.');
                });
                
              })
            }
          }
          
        })
        .controller('myCtrl',['$q', function($q){
          var vm = this;
          console.log("MYCTRL");
          vm.fun= function(){
            console.log('method called');
            // Create a promise here...
            var def = $q.defer();
            
            setTimeout(function(){
              console.log('done in controller');
              def.resolve();
              
              // Potential use of reject in case of error.
              // def.reject();
            }, 2000)
            
            return def.promise;
          }
        }])
<script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="76171811031a1704581c05364758405846">[email protected]</a>" data-semver="1.6.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="43212c2c37303731223303706d706d74">[email protected]</a>" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

<div ng-app="myApp">
  <div ng-controller="myCtrl as $ctrl">
  <button class="btn btn-primary" my-dir="$ctrl.fun()" after-value="Clicked" before-value="click" ng-disabled>Click</button>
  </div>
</div>

Update based on comments:

Upon clicking the button, the text should change, the button should be disabled, and the promise should be invoked by calling a function within the controller and not directly invoking the promise.

When you invoke $scope.myDir(), you are actually triggering a function that returns a promise, not directly invoking the promise itself. Clarify how you mean the promise should be "invoked".

Following the promise's success or failure in the controller, I intend to update the text on the button and enable it accordingly.

This behavior is handled within the .then() function. If the promise returned by myDir() resolves successfully, the status on the button will revert back. This process is implemented within the directive since it has knowledge about the button's state. Both success and error scenarios from the promise are accounted for.

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

Display the input text line by line

How can I achieve the desired output for this input parameter? displayText("you and me"); expected output: ["you and me", "you and", "and me", "you", "and", "me"] I have attempted ...

What is the best way to transfer information between two components in React.js by simply clicking a button?

One of the challenges I am currently facing involves rendering data from the Pokemon API in a table. Within this table, there is a button that allows users to select specific data when pressed. My goal is to send this selected data from the table component ...

Error: The React styleguidist encountered a ReferenceError due to the absence of the defined

After integrating react styleguidist into my project, I encountered an issue when running npm run styleguidist. The error message states: ReferenceError: process is not defined Here is a snippet from my styleguide.config.js file: module.exports = { ti ...

Merge requirejs modules using build script

I am attempting to merge and compress require modules into a single file. For instance, if I have a file named article.js with the following content: define(["jquery","flexslider","share_div"],function(){}); I wish for all these dependencies to be merge ...

Error: Unable to locate npm package

I am currently working on an Angular application that was created using Grunt and relies on Bower and NPM. Recently, I attempted to install an npm module locally. The installation resulted in the files being stored in the main application directory under ...

VueJS Vuetify automatically centers default content

Vue cli version @ 5.0.6 | Vuetify version: [email protected] I have been utilizing Vue.js and Vuetify for some time now, and I can't shake the feeling that not all Vue.js/Vuetify components default to centered alignment. I recently initialized a ...

AngularJS uses variables defined by using curly braces like {{"message"}}

I am currently utilizing the following code snippet to monitor route changes: $scope.$on('$routeChangeStart', function (event, toState, toParams, fromState, fromParams) { //content $log.log(toState); } Whenever I print out "toState ...

Troubleshooting the non-functioning addEventListener in JavaScript

I am facing an issue where a function that should be triggered by a click event is not working and the console.log message does not appear <script src="e-com.js" async></script> This is how I included the javascript file in the head ...

having difficulty sending the username and password from the HTML page to the controller in AngularJS

In my AngularJS controller, I am having trouble retrieving the values of the username and password fields after submitting the login form. Here is the HTML code for the form: <form class="form-signin" action="" method="post"> ...

Issue with Vue.js: Difficulty sending an array of values to an endpoint

I am currently in the process of learning Vue in order to complete my project, which has a Java Spring backend. The endpoint I am working with expects an object with the following values: LocalDate date; Long buyerId; Long supplierId; List<OrderDetails ...

Karma-coverage not detected: however, it is already installed

I utilized the following guide when configuring my Karma-coverage plugin. Additionally, it was locally installed through the package.json file which appears like this: { "name": "myApp", "version": "0.1.0", "devDependencies": { "karma ...

Error in Prisma: Unable to retrieve data due to undefined properties (attempting to access 'findMany')

Recently, I've been working on a dashboard app using Prisma, Next.js, and supabase. Encountering an issue with the EventChart model in schema.prisma, I decided to create a new model called EventAreaChart. However, after migrating and attempting to ex ...

Managing Import Structure in Turborepo/Typescript Package

I am currently working on creating a range of TypeScript packages as part of a Turborepo project. Here is an example of how the import structure for these packages looks like: import { Test } from "package-name" import { Test } from "package ...

Leverage AJAX data to dynamically generate an input field within a Laravel application

. Hey everyone, I'm currently working on implementing ajax for a search functionality. The goal is to display links to the search results' pages along with checkboxes next to each result, allowing users to select orders for printing. Although I ...

What is the method for adding a tag within a specific div ID in ExtJS?

I am looking to insert a new tag within existing tags using extjs, based on the div id 'task123', and also trigger an alert message accordingly. Below is the HTML code snippet: <div id="task123"> <div class="msg" id="sample"> ...

Creating unit tests for an Angular controller using Jasmine

When my controller loads in Angular, I have a set of initializations that need to be performed. Some are local while others involve making http calls. While writing test cases, I currently initialize the controller in each test case to check if variables ...

What is the best method for aligning buttons in a row with all the other buttons?

I have been attempting to display two buttons, id="strength" and id="minion", when a certain button, id="expandButton", is clicked. I want these two buttons to be positioned on either side of the button that triggers their cre ...

Definition file for Typescript Angular 1.5 component

Encountering a problem with typescript and angular 1.5 - when building, an error pops up saying error TS2339: Property 'component' does not exist on type 'IModule'.. Could it be that I overlooked a definition file containing this proper ...

The precompilation of Handlebars using Node.js encounters issues on Cloud9

I'm currently using the handlebars template precompiler for express, specifically this one, to precompile my templates in nodejs. While everything runs smoothly locally, I've encountered some issues when trying to do the same on Cloud9 IDE (Clou ...

Error: Module not found - Unable to locate 'dropzone'

Since migrating from Angular 4.4 to Angular 8.0, I encountered the following issue: ERROR in ./src/attributes/import/import.component.ts Module not found: Error: Can't resolve 'dropzone' in 'C:....\src\attributes\imp ...