Adjust scope values between two instances of a directive

My dilemma involves an aside that will appear as a pop-up modal, allowing users to interact and choose between two options. If the user decides to reject the offer, I want to hide both the pop-up modal and the overlay. Hiding the modal is not an issue - the ng-show function works perfectly. However, the overlay (a separate element in a different part of the codebase) does not update its display accordingly, even though it uses the same directive and value from a singleton. How can I ensure that they are both synchronized?
Here's the modal

    <aside data-ng-show="!customerRejectedOffer" data-pi-browser-update class="md-modal md-show pi-modal-message modal-effect-2">
<div class="pi-modal-content">
    <h4>Title</h4>
                <div>
                    <p>Copy</p>
                    <ul class="flush--left nav--no-style-type">
                        <li>
                        <button class="pi-modal-content-button wb-btn wb-btn--secondary">
                            <a class="pi-modal-content-link" href="#" title="Upgrade Button">
                            <admin:keyvalues key="datedbrowser.iebutton"/></a>  
                        </button>
                        </li>
                        <li><button class="pi-modal-content-button pi-modal-content-button__refusal" data-ng-click="rejectOffer()"><a class="pi-modal-content-link" title=""></a></button></li>
                    </ul>
                    <button data-ng-click="rejectOffer()" class="pi-modal-content-close md-close">X</button>
                </div>
            </div>
</aside>

To handle the show/hide values and click events, I've implemented a directive.

(function() {

  'use strict';


  angular
    .module('pi.common.browserupdateMessage', ['pi.common.storage'])
    .directive('piBrowserUpdate', browserUpdate);

  function browserUpdate(SharedScopeUtility) {

    return {
      link: browserUpdateLink
    };

    function browserUpdateLink(scope) {
      scope.customerRejectedOffer = SharedScopeUtility.hasAcceptedUpgrade;
      console.log(scope);
      scope.customerRejectedOffer = customerRejectedOffer;

       function rejectOffer()() {
        SharedScopeUtility.hasAcceptedUpgrade = true;
        scope.customerRejectedOffer = SharedScopeUtility.hasAcceptedUpgrade;
      }

    }

  }

}());

In the directive, I initialize the customerRejectedOffer value using a service called SharedScopeUtility.

(function() {

  'use strict';

  angular.module('pi.app.sharedscopeutility', [
    'ngResource'
  ])

  .factory('SharedScopeUtility', function (){

    var hasAcceptedUpgrade = false;
    var _service = {
      hasAcceptedUpgrade: hasAcceptedUpgrade
    };

    return _service;
  });

}());

When the user clicks the "Rejected Offer Button," the rejectOffer() function is triggered within the directive. This function updates the value on the service from false to true, and sets a new value on the scope called customerRejectedOffer, which is then used for ng-show. While this works for the pop-up modal, the overlay element:

<div data-pi-browser-update data-ng-click="rejectOffer()" data-ng-show="!customerRejectedOffer" class="pi-modal-overlay"></div>

Using the same directive and value for its ng-show, the overlay remains visible despite the changes. Although I utilized a service to make the rejectedOffer boolean come from a singleton, it still doesn't resolve the issue. Any assistance would be greatly appreciated :-)

Answer №1

  1. Take a look at this plunker for crucial information: Plunker Link. Make sure the data-ng-show is directly connected to the
    SharedScopeUtility.hasAcceptedUpgrade
    service flag. Add the SharedScopeUtility service to the scope by using
    scope.SharedScopeUtility = SharedScopeUtility
    .
  2. There seems to be an error in this line with an empty function being returned: function rejectOffer()()
  3. Define the rejectOffer() on the scope too, like so - scope.rejectOffer = function(){}
  4. In some cases, directives might require a $timeout to reflect scope changes, but you can avoid this by referring to a service as recommended above.

Best of luck and feel free to reach out if you need further assistance!

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

The mongoose find query is coming back with an empty array, even though there is data present in the

My goal is to update commodity data in my stockrecord collection by adding the quantity of a commodity if it already exists in the collection. However, I encountered an issue where the find method returns an empty array even for existing data. Here is th ...

Can you verify my comprehension of the process for iteratively displaying numerous custom Tree components in Vue.js 3?

While exploring the Vue.js documentation, I came across an example of iteratively rendering a Tree using the v-for directive. My aim was to modify the code to render multiple TreeItems in the App.vue file. I am puzzled by the fact that it is possible to i ...

Is there a way to implement a function in Javascript or CSS where hovering over a button will cause a div to scroll either left or right

I am working on creating a unique photo gallery layout with a description block positioned below the images. My goal is to incorporate two arrow buttons, one on each side of the photos, that will trigger a scrolling effect when hovered over - shifting the ...

Sending AngularJS data using the POST method to be retrieved in PHP's $_POST

After successfully implementing a post request from my AngularJS app to a PHP script, I am now trying to ensure that the data received in my php script is stored in the $_POST['jwt'] variable. Below is an example of my AngularJS code: var dataR ...

Stopping halfway through a jQuery toggle width animation to close again

Perhaps the question may be a bit unclear, but allow me to provide an example. When repeatedly clicking the button that toggles the width, the div continues to animate long after the button press, which is not visually appealing. My desired outcome is for ...

Is there a way to make JavaScript function properly with PHP-generated content?

I have a PHP file that loads a variety of forms depending on an identifier passed through a GET request. Everything is functioning properly, except for my JavaScript/jQuery code. Is there a way I can refresh the JavaScript to make it work with the form? ...

The value from the textbox is not being received by the JavaScript and PHP

I'm encountering an issue with my codes where they are not properly passing the value of the verification code from the textbox to JavaScript and then to PHP. I need assistance in resolving this issue. Below is the snippet of code: HTML: /* HTML c ...

Tips for generating an HTML template as a string using jQuery

I have developed a dynamic modal using plain JavaScript, triggered by a button click. This modal is controlled based on the attributes `data-open-hours` and `data-closed-hours` in the HTML. If you take a look at my demo, you will notice an issue. Let me e ...

Trigger the execution of the second function upon the successful completion of the first

In the following code, my concept is to display: The clicked kingdom (clicked_id) initiates an attack on (clicked_id). https://i.stack.imgur.com/Bx8QW.png https://i.stack.imgur.com/Cg2GL.png https://i.stack.imgur.com/gUNxM.png How can I trigger the sec ...

Adding a class to an element can be easily achieved when both input fields have values

Is it possible to apply the "active" class to the element go_back_right only when both inputs with classes search_box_name and search_box_id have content in them? I've tried looking for solutions on this platform, but being new to JavaScript, I couldn ...

Collecting values using AJAX in Codeigniter from an input file

I have been exploring examples of AJAX code, and I noticed that when using form-data in AJAX, we need to serialize each element individually. While normal data serialization works fine, I encountered an issue when trying to pass the value of an input file ...

contrasting the application of logic in Rails controllers versus JavaScript within the .js.erb files

When dealing with a large "data" active record object that needs to be filtered based on user interactions on a page, the question arises about where to place the data-filtering logic. Currently, the filtering is done in the rails controller action, simpli ...

Determine the time difference between two dates, taking into account Daylight Saving Time adjustments

If a start date and number of days are given, I need to calculate the end date by adding the number of days to the start date. This is the code snippet I used: var endDate=new Date(startDate.getTime()+ONE_DAY); Everything was working fine until I notice ...

An error occurs with Three JS when trying to access a S3 Bucket used as a CDN due to Cross Origin

function displayItem() { startScene(); THREE.ImageUtils.crossOrigin = "anonymous"; var mtlLoader = new THREE.MTLLoader(); mtlLoader.setTexturePath('https://cdn.rubyrealms.com/textures/'); mtlLoader.setPath('https://cdn.ru ...

Ways to prevent endless loops from occurring?

Here is the code for my component: const Inscriptions = () => { // getting state const { inscriptions, loading } = useSelector( state => state.user ); // flag const instances = Object.keys(inscriptions).length; // dispatch ...

Numerous navigable tabs all on a single page

After following a tutorial on YouTube to create scrollable tabs, I successfully implemented it using Bootstrap 5. However, I'm facing challenges in getting multiple scrollable tabs to function on a single page. Although the tabs and tab-content are fu ...

A guide to showing the value of a selected checkbox in Vue.js

Here is a link to the reference: https://jsfiddle.net/8xom729c/ <div class="checkbox-alignment-form-filter"> <input type="checkbox" id="HR 3502 : 2004" class="vh-product" value="HR 3502 : 2004" v-model="checkboxestwo[0]" v-on:click="checkAllt ...

Error: Issue determining the type of variable. Unable to eliminate type 'any'

I am trying to load some widgets from a template object (possibly JSON in the future). Here's an example: type RectangleTemplate = { name: 'Rectangle'; props: { width: number; height: number; } }; type ButtonTemplate = { nam ...

How to fetch JSON data from a URL in Angular 2

let headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); let ep = './data.json'; this.events = this.http .get(ep, { headers: headers }) .map(res => res.json()) .map(({results}: ...

The persistent state is not being saved correctly by Redux-Persist and is instead returning the initial

I have included redux-persist in my project, but for some reason it is not persisting the state as expected. Instead, I keep receiving the initial state whenever I reload the page. Below is the snippet of my root-reducer: import { combineReducers } from & ...