Monitoring changes within a factory

Hey there! I've got this shared_service factory that's being used by my menu and other elements on the page.

angular.module('shared_service', []).
    factory('Shared', function($scope){
        var shared_service = {
            something: 'something',
            something_else: 'something_else'
        };

        //I'm looking to set up a watcher for 'something' in order to update 'something_else'
        //$scope.$watch('shared_service.something', function(){
        //    something_else += 1;
        //}
        return shared_service;
});

I know I could potentially attach the watcher in a controller, but personally, I feel like it belongs here. Do you think it's feasible to have it here?

Appreciate any advice or input you might have. Thanks!

Answer №1

If you want to monitor changes in the application, you can use $watch on the $rootScope. However, since it's not within a controller, you must watch the return value of a function. Here is an example implementation:

angular.module('shared_service', []).
  factory('Shared', function($rootScope){
    var shared_service = {
        something: 'something',
        something_else: 'something_else'
    };

    $rootScope.$watch(function() {
      return shared_service.something;
    }, function () {
             shared_service.something_else = shared_service.something_else + 1;
    });
    return shared_service;
  });

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 there a way to smoothly navigate back to the top of the page after the fragment identifier causes the page to scroll down?

I do not want to disable the functionality of the fragment identifier. My goal is for the page to automatically scroll back to the top after navigating to a specific section. This inquiry pertains to utilizing jQuery's UI tabs. It is crucial to have ...

React-Redux Error: The function this.props.AppendCharacter is not defined

I have been looking for a solution to my issue but couldn't find anything that matches it. I am working on creating a calculator app using React & Redux, and whenever I click on one of the number buttons, I receive an error message saying "this.props. ...

Displaying the URL of a link on the screen using jQuery

I am looking for a solution to add a link address after the link itself in a table containing reference links for our staff. I have used CSS to achieve this in the past, but the address was not copyable by users. Instead, I am interested in using jQuery&ap ...

React: Unexpected behavior when modifying a variable's state using post-increment

When I utilize the post-increment operator to change the state variable, the count variable retains its old value... Allow me to illustrate this with an example app: When I click the button with the following code, the app displays the following sequenc ...

Tips for halting click propagation in VueJS

My dilemma lies within a recursive list (tree) where each element contains a @click="sayHello(el.id)". The challenge arises due to the nested structure of the list, such as: list-element-0-01 ├──list-el-1-01 │ └──list-el-2-01 └──list ...

Strangely odd actions from a JavaScript timepiece

After answering a question, I encountered a problem with my JavaScript clock that displays the day, time, and date on three lines. To make sure these lines have the same width, I used the BigText plugin, which works well except for one issue. tday=new A ...

JavaScript and Angular are used to activate form validation

Update: If I want to fill out the AngularJS Forms using the following code snippet: document.getElementById("username").value = "ZSAdmin" document.getElementById("password").value = "SuperSecure101" How can I trigger the AngularJS Form validation befo ...

Quiz results are incorrect

I've been working on creating a quiz application using JavaScript only, but I'm encountering an issue with the scoring. Initially, I set the correct variable to 0 and intended to increment it by 1 each time a correct answer is selected. However, ...

Tips for invoking a Laravel Model function with a parameter in a Vue.js template

I'm facing an issue with displaying stock quantities for products in a Vue.js template. I have a product table and stock table where data about product sale and purchase are stored. I need to calculate the stock of each product based on purchase and s ...

An issue occurred while serializing or deserializing, specifically with the JavaScriptSerializer and

I am facing an issue while trying to retrieve images from my database. The process works smoothly with small images, but when attempting to do the same with the default Windows 7 images (Desert, Koala, Penguins, Tulips, etc.), I encounter an error: "Err ...

Difficulty Converting Array of Objects to Proper Type with Q.Promise and KO.mapping

I have encountered an issue while trying to filter an observable array. It seems that the ko.utils.arrayFilter method is converting all my model's field names to lowercase, causing unexpected behavior. I should mention that this project involves Types ...

Experiencing problems with the Datepicker and cloning functionality in JQuery?

This is the section of code responsible for cloning in JavaScript. $(document).on("click", ".add_income", function () { $('.incomes:last').clone(true).insertAfter('.incomes:last'); $(".incomes:last").find(".income_date_containe ...

Vue Method always executed (regardless of click event)

I'm fairly new to vue and still getting a grasp on the fundamentals of my code. Currently, I am facing an issue with a Method. It should only trigger when the user clicks on the button, but it seems to be triggered all the time. I even tried adding ...

Managing route rendering in nuxtjs: A guide

I came across Goldpage, a tool that allows for route rendering control. Render Control - With Goldpage, you have the flexibility to choose how and when your pages are rendered. For example, one page can be rendered to both HTML and the DOM (classic serv ...

Tips for duplicating specific div elements

Is there a way to create copies of selected divs within the same panel using a Javascript report designer? I attempted to achieve this by using the following code snippet: function DesignerClone() { $(".ui-selected").each(function () { va ...

Receiving POST data in the req.body object with only the key specified in Express.js

I am encountering an issue with my current POST request. There is a simple function in place that handles the sending of data to the server using AJAX. handleSubmit(event) { var http = new XMLHttpRequest(); // object allows for making http requests // ...

Numerous asynchronous requests

I'm trying to figure out why the application keeps making multiple ajax calls. Check out this directive: gameApp.directive('mapActivity', function() { return { restrict: 'A', link: function(scope, element, att ...

Is there a way to extract just the date portion from the string "2017-11-13T00:00:00" using AngularJS?

I am looking for a way to extract only the date portion from "2017-11-13T00:00:00" using AngularJS. I attempted to achieve this using the following method: &scope.date = "2017-11-13T00:00:00"; var dateParts = $filter('date')(new Date(&sc ...

Receive the most recent query in a Nuxt plugin following the completion of page loading

So, here's the issue - I have a plugin containing some functions that are supposed to update URL queries. However, every time I run $global.changePage(2) or $global.changeLimit(2), the console.log(query) outputs an empty object and doesn't show t ...

What is the best way to utilize mapping and filtering distinct values in an array using TypeScript?

What is the best way to filter and map distinct elements from an array into another array? I've experimented with various methods but keep encountering a syntax error stating "Illegal return statement". My objective is to display only unique items f ...