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

Differences Between Android and JavaScript: Ensuring Library Validity

Validation in JS is provided by the validator library which can be found at https://www.npmjs.com/package/validator Is there an equivalent library for validation in Android? If so, what is the name of Android's library? ...

Use VB.NET to dynamically update cell content in HTML

Can you assist me with updating cellContent in HTML using vb.net? The DataGrid view is on a website. Below is the inspected HTML: <div class="grid-controls"> <form method="post" class="vss-app-form grid-control-popover none" id="gridMorePopov ...

JSON object fails to iterate with ng-repeat

It must be the scorching temperature... Having a json object that I'm eager to loop through using ng-repeat, it should be straightforward, but alas! it's just not cooperating. Here's the HTML snippet: <a data-ng-repeat="x in template.m ...

SimpleLightBox refuses to function

Having trouble getting SimpleLightBox to work properly? It seems like when you click on an image, it opens as a regular image on a blank page. I've added the JS and CSS files correctly (I double-checked in the source code) and included the HTML and JS ...

Divide the division inside the box by clicking on it

I am looking to create a unique div with a random background color and a width of 100px. Additionally, I want to have a button that, when clicked, will split the original div into two equal parts, each with its own random background color. With each subs ...

Tips for combining values with Reactive Forms

Is there a way to merge two values into a single label using Reactive Forms without utilizing ngModel binding? <label id="identificationCode" name="identificationCode" formControlName="lb ...

Strange behavior: JS object values disappear when accessed statically

I'm feeling puzzled. The issue at hand is that an object seems to lose its values within a loop based on the method of access. When accessed through variables, everything appears to be in order. However, when using static expressions identical to the ...

Change the label's class when the input area is selected

Looking to add a new class to a label when its corresponding input element is in focus. A form consists of 10 input fields and 10 labels, one for each field. const inputFields = document.querySelectorAll('.form-control'); console.log(inputFie ...

Finding and retrieving the checked checkboxes in Selenium WebDriver without using the name or xpath

Can you help me figure out how to identify the selected checkbox from a list of checkboxes when no name or xpath is provided? Here is an image of the checkbox: enter image description here This is the HTML code generated: <div class="c ...

Creating Vue3 Component Instances Dynamically with a Button Click

Working with Vue2 was a breeze: <template> <button :class="type"><slot /></button> </template> <script> export default { name: 'Button', props: [ 'type' ], } </scr ...

Unable to access JQuery Draggable method within partial view

In my partial view, I have multiple Divs that are designed to be draggable using the JQuery UI draggable library. The JQuery scripts are included in the master page, and when I view the partial view on its own, everything works fine. However, when I load ...

Is it feasible to capture a screenshot of a URL by using html2canvas?

Is it possible to take a screenshot of a specific URL using html2canvas? For example, if I have the following URLs: mydomain.com/home mydomain.com/home?id=2 mydomain.com/home/2 How can I capture and display the screenshot image on another page? window ...

Error in ng-repeat loop: detecting duplicates when none are present

$scope.subjects = [ "Computer Security", "Graphics and Multimedia", "Networks", "Computer Science and Engineering", "Game Design", "Programming", "Information Technology", "Software Engineering", "Technology Manageme ...

Decoding a JSON object in node.js

{"__v":0,"_id":{"$oid":"55f13d34258687e0bb9e4385"},"admin":true,"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b3d6ded2c3dfd682f3d4ded2dadf9dd0dcde">[email protected]</a>","last_login":"11:25:24 AM","name ...

Getting the parameter route value from Laravel and passing it to Ajax

Need help with returning the parameter of a Laravel route to an AJAX response. Here is the relevant code: public function getPermissions(Request $request) { //$v = request()->route()->parameters('profile'); $v = request()-& ...

Subtracting Arrays Containing Duplicates

Imagine having two arrays defined like this: const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr'] const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa&ap ...

Is there a way to dispatch an event from one Angular ui-router view to another view?

In order to change the login button to display "logged in as xxx" after authentication, I have structured my page into three views: header, content, footer. The login button is located in the header view. Upon clicking login, it transitions to the "app.log ...

Click a button to spin images around

Is there a way to rotate an image by 90 degrees, 180 degrees, and 360 degrees with the click of a button? <img class="test" id="image" src="images/image" alt="This is the Display Image" /> I attempted to use the following script, but was not satisf ...

`@keyup.enter event listener will only be triggered upon pressing the Enter key if the focus is on

My login button only seems to work when I press the tab button after entering my email and password. I would like it to work whenever I press the enter key while on the Login page of this VueJS application. This is the HTML template: <template> ...

What is the best way to display three unique maps simultaneously on separate views?

In this scenario, I have incorporated three separate divs and my goal is to integrate three maps into them. The javascript function that controls this process is as follows: function initialize() { var map_canvas1 = document.getElementById('map_canva ...