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

Updating the URL-path in the Angular file-upload module: A step-by-step guide

When working on my project, I came across a helpful module that I use from https://github.com/nervgh/angular-file-upload. It functions well when the URL is set during initialization. However, I encountered an issue when trying to change the URL after the ...

Angular Custom Pipe - Grouping by Substrings of Strings

In my Angular project, I developed a custom pipe that allows for grouping an array of objects based on a specific property: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({name: 'groupBy'}) export class GroupByPipe impleme ...

The Magnificent jQuery Widget Factory's _trigger Instance

When utilizing the _trigger function to initiate events, I often come across a recurring issue that I struggle to fully comprehend. The problem arises when there are multiple instances of my widget on the same page. In such cases, the most recently instan ...

Vue.js Dynamic Class Binding Fails to Update

As I delve into learning Vue Js, I have been working on a simple todo app. One interesting thing I've done is binding a class to my todo items based on whether todo.completed is true or not: <a v-bind:class="{iscomplete : todo.completed}& ...

A mysterious JavaScript snippet that automatically scrolls down when the webpage is loaded

Recently, I encountered an issue with a mysterious JavaScript script that automatically scrolls down when entering the page (I suspect it's JavaScript). I've tried to investigate using Firebug, examining the code, deleting scripts, and even remov ...

Can variables be bound bidirectionally between nested isolated scopes?

Looking into the complexities of nested directives, I am facing a challenge in establishing two-way binding between isolate scopes. The main goal is to have the outerPower variable bind to the innerPower variable and update whenever the innerPower value i ...

Slicknav is failing to appear on the screen, although it is being

After spending hours trying to implement a slicknav menu into my school project, I'm stuck and seeking guidance. Despite having some coding experience, I can't seem to find the solution to my problem. Any help, insight, or tips on fixing or impro ...

Sending a request in Vue.js and not receiving a defined response

As a beginner in VueJs and Expressjs, my goal is to create the frontend using Vuejs and backend using ExpressJs. When I send a post request to the backend (ExpressJs), I encounter the following issues: 1- Response from the server is undefined. 2- In Chrom ...

Exploring the capabilities of ion-side-menu in conjunction with the Ionic header

<ion-view> <div ng-if="showHeader"> <ion-header-bar class="bar bar-header navbar-fixed-top"> <div class="row"> <div> <span class="navbar-brand" href="#"> //data </span> ...

Is it possible to include two functions within a single HTML script?

On my webpage, there are multiple tabs that display different sets of data. Below is the code for handling the functionality of these tabs: function openTab(event, tabName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassNa ...

A guide to eliminating duplicate values within an array and across multiple arrays with the help of jQuery

Looking for assistance with jQuery to find and alert repeated values in my code. Below are example arrays: a1 = {1,2,3,4,5,6,4} a2= {9,8,7}, a3= {a,b,c,d,e,7} I want to identify the value 4 in array "a1" and give an alert, as well as identify the value ...

What steps do I need to follow to write this function in TypeScript?

I am encountering a problem when building the project where it shows errors in 2 functions. Can someone please assist me? The first error message is as follows: Argument of type 'IFilmCard[] | undefined' is not assignable to parameter of type &a ...

Is there a way to automatically trigger a function once another function has completed its execution?

I am diving into the world of JavaScript as a beginner. All I want to do is trigger the function called seconOne() right after the execution of firstOne(). Specifically, I need the function two to be invoked when the value of p1 reaches 4. While I can us ...

When a node sends a request to an endpoint, it receives a response from

In my project, I have a file named "forms.routes.js" which contains a variety of endpoints using router.get, router.post, router.put, and router.delete. Interestingly, when I try to access the 16th endpoint in the list: localhost:3000/v2/forms/:domain/co ...

What is the best way to apply index-based filtering in Angular JS?

I am working on a tab system using ng-repeat to display tabs and content, but I'm facing some challenges in making it work seamlessly. Below are the tabs being generated: <ul class="job-title-list"> <li ng-repeat="tab in tabBlocks"> ...

Tap and conceal feature on a mobile website

I seem to be facing a JavaScript challenge. On the desktop version of my website, I've managed to create a functionality where hovering over a button reveals some text, and clicking anywhere else on the site hides the text. However, I'm now stru ...

Shopify module is throwing an error stating that React is not defined

I wanted to create my first Shopify module, but I encountered an error in my application page on the shop while using React. https://i.sstatic.net/Q02yM.png Here is my index.js code: import {Page} from "@shopify/polaris"; import {ResourcePicker ...

Creating a Vue component that leverages the computed property from a mixin

My situation involves a straightforward component that utilizes a mixin shared across various components that have similar functionalities. However, upon running it, an issue arises: The error message "Property or method 'activeClass' is not ...

What is the most effective way to divide input elements into an array in Angular?

How can I bind an input value to an ng-model as an array? For example, if I enter one, two, three, I want the resulting model to be [ "one","two","three" ]. Currently, this is my approach: <input type="text" ng-model="string" ng-change="convertToArra ...

Discover the best way to implement aliases for embedded base 64 images within HTML code

I am trying to incorporate Base64 embedded images into my HTML file, but the image sizes are over 200k, making the base64 data part very large. To address this issue, I would like to place these images in another tag, such as a script, and attach them at ...