Tips for monitoring a variable within a Service using a Controller to trigger a modal?

http://plnkr.co/edit/bdHiU0?p=preview


When I require a variable that is returned by a service, like the data in

InitTickersFactory.returnTickers()
, I can easily assign it to vm.tickersObject. However, in the plnkr example provided above, I am simply toggling a variable in my tickerController and then passing it on to be stored in AddTickerFactory.

Click on the open modal button to view the logs.

Now, I need my tickerModalController to retrieve this variable and decide whether to display or hide a modal. Unfortunately, vs.showModal in my tickerModalController remains stuck at false:

vs.showModal = AddTickerFactory.getToggleStatus();

Markup

<ticker-modal></ticker-modal>
<tickers-panel></tickers-panel>

Full code

// Code goes here

angular.module('app', [])

.directive('tickersPanel', function() {
    return {
    restrict: "E",
    link: function($scope, el, attrs) {
      // console.debug($scope, attrs);
    },
    template: '<div class="ticker" ng-controller="tickerController"><button ng-click="openModal()">Open Modal</button></div>'
  };
})

.directive('tickerModal', function() {
    return {
    restrict: "E",
    link: function($scope, el, attrs) {
      // console.debug($scope, attrs);
    },
    template: '<div class="modal" ng-show="showModal" ng-controller="tickerModalController"><h1>Hello World!</h1></div>'
  };
})

.factory('AddTickerFactory', [function() {
    var vm = this;
        vm.addTickerToggle = false;

    var addTicker = {
        toggleAddTicker : toggleAddTicker,
        getToggleStatus : getToggleStatus
    }

    return addTicker;

    function toggleAddTicker(bool) {
      console.log(bool);
      vm.addTickerToggle = bool;
    }

    function getToggleStatus() {
        return vm.addTickerToggle;
    }
}])

.controller('tickerController', 
  ['$scope',
   'AddTickerFactory',
   function($scope,
            AddTickerFactory) {

  var vs = $scope;
      vs.addTicker = false;

  vs.openModal = openModal;

  function openModal() {
        vs.addTicker = !vs.addTicker;
        AddTickerFactory.toggleAddTicker(vs.addTicker);
  }
}])

.controller('tickerModalController', 
  ['$scope',
   'AddTickerFactory',
   function($scope,
            AddTickerFactory) {

  var vs = $scope;
      vs.showModal = false;

  vs.showModal = AddTickerFactory.getToggleStatus();
  console.log('vs.showModal',vs.showModal);

  vs.displayModal = displayModal;

  function displayModal() {
    vs.showModal = !vs.showModal;
  }
}]);

I attempted to set up a watch, but it does not detect any changes:

vs.showModal = AddTickerFactory.getToggleStatus();
console.log('vs.showModal',vs.showModal);

$scope.$watch('vs.showModal', function(current, original) {
    console.log('current',current);
    console.log('original',original);
});

Answer №1

Another way you can use $watch is by passing a function like this:</p>

<p><a href="http://example.com/sample-code" rel="nofollow">http://example.com/sample-code</a></p>

<pre><code>  $scope.$watch(function(){
    return MyDataFactory.getStatusUpdate();
  }, function(current, previous) {
    vm.showPopup = current;
      console.log('current',current);
      console.log('previous',previous);
  });

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

Is it more beneficial to categorize REST-based modules/controllers by resource or by specific action/feature?

I'm facing a scenario that goes like this: Endpoint 1: Retrieve all books in the United States owned by John with a GET Request to /country/us/person/john/books Endpoint 2: Get all books owned by John in every country with a GET Request to /person/j ...

Utilizing Template Styling for Iterating through Lists in Vue.js

I would like the output format to display one player value followed by one monster value, repeating this pattern for each pair of values. new Vue({ el: app, data: { output: { player: [1, 5, 61, 98, 15, 315, 154, 65], monster: [2,14, ...

Gliding along a div and concealing it out of view, making it seem like it has disappeared

I attempted to slide down the ".preloader" div after a 2-second delay using JQUERY, but I couldn't get it to work as expected. I didn't want to use a toggle button for this effect. I also experimented with creating an animation using @keyframes, ...

Use ng-repeat to extract information from an array and populate it into a datalist

I've already tried searching for a solution to my issue on Google, but I couldn't find anything that really helped me. I'm looking to create an input field that also functions like a dropdown. This way, I can either type in my own data or se ...

``There seems to be an issue decoding the JSON array

I am currently working on a PHP script to decode JSON data and insert the objects into my database. However, I am encountering an error: Fatal error: Cannot use object of type stdClass as array in phptest.php on line 21 $postdata = file_get_contents("php: ...

How a JavaScript function handles the scope of a for loop index

Here's some Javascript code I'm working with: func1() { for(i = 2; i < 5; i ++) { console.log(i); func2(i); } } func2(x) { for(i = 100; i < 200; i ++) { do something } } I've noticed that when runni ...

Encountering a surprise Illegal Token JS Error

I am encountering a persistent "Unexpected Token ILLEGAL" error while attempting to run the script on the page after it has been registered. StringBuilder str = new StringBuilder(); str.Append("<script type='text/javascript&apos ...

Create a PDF document using HTML code stored on a separate component within an Angular 2 application

I am facing an issue with my parentComponent and childComponent setup. Specifically, I have a button called downloadPDF in the parentComponent that is supposed to trigger a PDF download from the HTML code of the childComponent without displaying the childC ...

Change the position of an array element when displayed on an HTML page

I'm trying to figure out a way to manipulate the position of an HTML element that is stored inside an array. The issue I am facing is that my code generates a new div every time a specific function is called, and this div has a class applied to it for ...

Identical manipulator distinct infusion

I am looking to create multiple controllers that share the same logic, with only differences in injections. One way to achieve this is by creating controllers using a common function like so: var controllerFunc = function($scope, service) { $scope.se ...

Steps to replace the content of an HTML file (such as modifying images) by clicking on an element in a separate HTML file

Currently, I am in the midst of a project and wondering if it is possible to dynamically modify the content of an HTML file, such as images and text, using JavaScript. My goal is to achieve this without relying on any frameworks, simply by clicking on el ...

Developing a downloadable PDF version of an online platform

For weeks now, I have been tirelessly searching for a solution to a problem that has stumped me once before. The Challenge: My company created a sophisticated web-based data analytics suite for a major beverage distributor. Our client is now requesting a ...

Is it possible to share an .ics file using SparkPost in a Node.js environment?

Attempting to generate an i-cal event and link it to a sparkpost transmission in the following manner: const event = cal.createEvent({ start: req.body.a.start, end: req.body.a.end, summary: req.body.a.title, description: req.body.a.body, ...

Encountered an issue while integrating CKEditor 5 into a standalone Angular 17 application: "Error: window is

Having trouble integrating CKEditor with my Angular app (version 17.1.2 and standalone). I followed the guide step by step here. Error: [vite] Internal server error: window is not defined at r (d:/Study/Nam3_HK3/DoAn/bookmanagement/fiction-managemen ...

There was an issue with the parsing of the module in ansi-html 1:0 due to an unexpected character "#" at the beginning of the line

I've been delving into learning angular js. Whenever I try to run ng serve --open, I encounter the following error: ERROR in ./ansi-html 1:0 Module parse failed: Unexpected character '#' (1:0) You may need an appropriate loader to handle th ...

What is the best way to enable an image to be moved on top of another image?

Is there a way to allow users to drag around an image that is positioned on top of another image in an HTML file? I want the superimposed image to stay within the boundaries of the underlying image. Any suggestions on how this can be achieved? <html& ...

Storing the state of DevExtreme DataGrid in Angular

Currently, I have integrated the DevExtreme DataGrid widget into my Angular application. Here is a snippet of how my DataGrid is configured: <dx-data-grid id="gridContainer" [dataSource]="employees" [allowColumnReordering]="true" [allo ...

What could be causing my default prop to not be transmitted to the child component in vuejs2?

Having trouble passing a default value to my Leaflet map child component before fetching the desired data from an API endpoint. I tried using country coordinates like latitude and longitude, but it's not working as expected. This is how I attempted t ...

Using Modal Functions in AngularJS Controller

I have been working on a project that utilizes the ui.bootstrap. As per the instructions from the tutorial I followed, my setup looks something like this: 'use strict'; angular.module('academiaUnitateApp') .controller('EntryCtr ...

SpineJS combined with Express

Are there any recommended tutorials or case studies showcasing the integration of SpineJS and Express in applications? I have experimented with both technologies, but am currently facing some challenges. My backend is set up to run Express by using coffee ...