Use Angular.js to perform navigation after clicking the "Ok" button on a confirmation box

I encountered a problem with my requirement. I need a confirm box to appear when the user attempts to navigate to the next state/page. Only if the user clicks on the "Ok" button should it proceed to the next state; otherwise, it should stay as it is. Below is an explanation of my code.

<li ui-sref-active="active" ><a ui-sref=".profile" confirm="Are you sure to move into the next page?">Profile</a></li>
<li ui-sref-active="active"><a ui-sref=".dept" >Department</a></li>

For example, if the user clicked on the profile menu, a confirm box will appear first, and upon pressing Ok, it will proceed.

 dashboard.directive('confirm', function(ConfirmService, $state) {
    return {
        restrict: 'A',
        scope: {
            eventHandler: '&ngClick'
        },
        link: function(scope, element, attrs){
          element.unbind("click");

          element.bind("click", function(e) {
            e.preventDefault(); // block the href generated by ui-sref
            ConfirmService.open(attrs.confirm, $state.go(attrs.uiSref)); // pass ui-sref into $state.go
          });
        }
    }
});

dashboard.service('ConfirmService', function($uibModal) {
  var service = {};
  service.open = function (text, onOk) {
    var modalInstance = $uibModal.open({
      templateUrl: 'myModalContent.html',
      controller: 'ModalConfirmCtrl',
      resolve: {
        text: function () {
          return text;
        }
      }
    });

    modalInstance.result.then(function (selectedItem) {
      onOk();
    }, function () {
    });
  };

  return service;
})

dashboard.controller('ModalConfirmCtrl', function ($scope, $uibModalInstance, text) {

  $scope.text = text;

  $scope.ok = function () {
    $uibModalInstance.close(true);
  };

  $scope.cancel = function () {
    $uibModalInstance.dismiss('cancel');
  };
});

Updated JavaScript Code

dashboard.directive('confirm', function($uibModal, $state,$timeout) {
    return {
        restrict: 'A',
        scope: {
            eventHandler: '&ngClick'
        },
        link: function(scope, element, attrs){
        var isConfirmed = false;

        element.bind("click", function (e) {
            if (!isConfirmed) {
                e.preventDefault();
                $uibModal.open({
                    templateUrl: 'myModalContent.html',
                    controller: function ($scope, $uibModalInstance) {
                        //$scope.text=text;
                        $scope.ok = function () { $uibModalInstance.close(); }
                        $scope.cancel = function () { $uibModalInstance.dismiss(); }
                    }
                })
                .result.then(function () {
                    isConfirmed = true;
                    $timeout(function () {
                        element.click();
                    });
                });
            }
        });
    }
    }
});

In this version, the confirm box still appears, but the issue is that it moves to the profile state first before showing the confirm box. I want the confirm box to display before navigating to the next state, and only after pressing Ok, it should proceed. I tried using ng-click, but it misses the active class and cursor:pointer property on the menu. Any assistance in resolving this issue would be greatly appreciated.

Answer №1

Update: I underestimated the complexity of parsing ui-sref for use in $state.go. Ultimately, I decided to simulate "clicking" on the element again...

    link: function(scope, element, attrs){
        var isConfirmed = false;

        element.bind("click", function (e) {
            if (!isConfirmed) {
                e.preventDefault();
                $modal.open({
                    template: '<div ng-click="close()">yes</div><div ng-click="dismiss()">no</div>',
                    controller: function ($scope, $modalInstance) {
                        $scope.close = function () { $modalInstance.close(); }
                        $scope.dismiss = function () { $modalInstance.dismiss(); }
                    }
                })
                .result.then(function () {
                    isConfirmed = true;
                    $timeout(function () {
                        element.click();
                    });
                });

                // see if these 2 lines make any difference
                e.stopImmediatePropagation();
                return false;
            }
            else {
                isConfirmed = false; // switch back to popup next time
            }
        });
    }

This segment is outdated

You can attempt something like this (not tested)

dashboard.directive('confirm', function(ConfirmService, $state) {
    return {
        restrict: 'A',
        scope: {
            eventHandler: '&ngClick'
        },
        link: function(scope, element, attrs){
          element.unbind("click");

          element.bind("click", function(e) {
            e.preventDefault(); // block the href generated by ui-sref
            ConfirmService.open(attrs.confirm, $state.go(attr.uiSref)); // pass ui-sref into $state.go
          });
        }
    }
});

Note: This is just a concept demo. You may need to add conditional statements for switching between ng-click and ui-sref.

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

Simulated actions in AngularJS service (evaluation and imitations)

I developed a service that provides various functionalities: 'use strict'; var app = angular.module('ns.simple-resource', []); function simpleResource ($q) { this.resource; this.loading; this.list; this.element; this.cget ...

Features of ES2015's [[class]] attribute

I've been developing a basic clone function var shallowCopy = function (value) { // In ES2017, we could also use // return Object.create(Object.getPrototypeOf(value), Object.getOwnPropertyDescriptors(value)); let propDescriptors = {}; for (le ...

Having Trouble Loading Vue Devtools in Vue Electron Builder

I'm encountering an issue with loading Vue Devtools in my Electron application integrated with Vue. This is my first time working with this combination, and I suspect there might be a dependency problem causing the Devtools not to load within the Elec ...

Start up a server-side JavaScript instance utilizing Express

My journey into web programming has led me to learning JavaScript, Node.js, and Express.js. My ultimate goal is to execute a server-side JavaScript function (specifically a function that searches for something in a MySQL database) when a button is pressed ...

Utilize the HTML img tag in conjunction with AngularJS and Ionic to showcase dynamic images

Currently, I am working on a hybrid mobile app using ionic and Angularjs. I am facing an issue with displaying images through the img html tag in my app. The main layout of my page includes a carousel at the top that displays images and a list containing s ...

Exploring the capabilities of referencing MongoDB documents with the populate method in Node.js

I have been working on referencing in Node.js using the populate method, but I am unsure about how exactly it works. In my code, I am creating a reference to the user collection from my child collection. I have two collections - one for children and anothe ...

Trigger Function on Input Change in Angular 2

Key aspects of component nesting: export class Child { @Input() public value: string; public childFunction(){...} } Main component responsibilities: export class Parent { public value2: string; function1(){ value2 = "a" } function2( ...

Maintaining the dropdown in the open position after choosing a dropdown item

The dropdown menu in use is from a bootstrap framework. See the code snippet below: <li id="changethis" class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown>LINK</a> <ul class="dropdown-menu"> <li id ...

A guide on traversing a HTML table and cycling through its contents with JavaScript

I'm currently in the process of constructing a grid with 20 rows and 20 columns of squares, but I am encountering difficulties with looping through table values to effectively create the grid. For more detailed information on the html code, please se ...

The dynamically generated table will only show the most recently added data

Currently, I am delving into the world of JavaScript to tackle an interesting challenge. Here's the scenario: I have a dropdown list populated with stream names derived from an array. Whenever a selection in this array changes using `onchange()`, I wa ...

Is there a way to efficiently eliminate the button label from my dataset without causing any disruptions to my chart

I am looking to remove a specific label from my chart, but whenever I try to do so, it impacts the entire functionality. var ctx = document.getElementById("CountryChart");<br> var myChart = new Chart(ctx, {<br><br> type: 'bar&ap ...

Javascript and iframes may encounter compatibility issues with browsers other than Internet Explorer

My HTML file includes an iframe and JavaScript that function correctly in IE Browser, but they do not work in other browsers such as Safari and Firefox. When using Safari, only the iframe box is displayed without showing the content inside it. I am curio ...

Troubleshooting Problems with POST Requests in ExpressJS

Currently, I am working on developing a feature in NodeJS that allows users to upload files. However, I am encountering difficulties while attempting to make a simple POST request. In my index.ejs file, I have written code that generates a form and initia ...

What is the method for invoking a function with arguments within an HTML `<p>` element?

I am looking to display like and dislike percentages on cards. <v-card v-if="software[2] == searched || searched == ''" class="software-card" > <h3>{{ software[2] }}</h3> ...

Function being called by Intersection Observer at an inappropriate moment

After running the page, the intersection observer behaves exactly as desired. However, upon reloading the page, I am automatically taken back to the top of the page (which is expected). Strangely though, when the viewport interacts with the target elemen ...

Show where the image should be placed according to the coordinates of the mouse click

My project begins with a blank canvas, prompting the user to click anywhere on the page to reveal an image. My goal is to show an image at the exact location where the user clicks. Although I can successfully trigger an image to appear in the corner of the ...

I'm looking for help on creating a three-column table using javascript/jquery. The table should display Product, Price, and Discount (which is calculated at 20%). Can anyone

Check out this code snippet. var items = ["Laptop", "Tablet", "Smartphone", "Headphones", "Camera"]; var costs = [599.99, 299.99, 799.99, 149.99, 499.99]; displayItems = ""; totalCost = 0; for (var j = 0; j < items.length; j++) { displayItems += " ...

Is it possible that updating AngularFire leads to scripts failing to function properly?

Having an issue with a script that reads data from Firebase using AngularFire, Firebase, and Angular. The problem arises when upgrading from version 0.7.1 to 0.8.0 of AngularFire, causing the script to stop working without clear indication of error. <b ...

Creating a list of identical elements with shared attribute values using nightwatch.js or JavaScript - a step-by-step guide

I have been using nightwatch.js for automating tests on a web application, and I am facing difficulties in creating a list of elements that share common values in their attributes. Below is an example: The first three spans with a common value for the att ...

What is the most effective way to set userForm.$dirty to true in AngularJS?

I am trying to set the dirty value of a form to true using $scope.userForm.$dirty = true; However, it does not seem to be working. Can someone please assist me with this issue? Thank you. ...