Alert AngularJS $watchCollection when changes occur in the model being observed by$watch

Currently, I have a $watch function that is listening for an input and then calling a service to retrieve new data. This returned data is essential for another function called $watchCollection.

My dilemma lies in finding a way to notify the $watchCollection function that a $watch has occurred, so that it can update the scope accordingly.

Below is a snippet of my HTML code:

<div ng-controller="MainCtrl">
    <p>A: <input type="text" ng-model="input"></p>
    <p>B: <input type="text" ng-model="output"></p>
</div>

Here's my JavaScript code:

angular.module('testapp', [])
.controller('MainCtrl', ['$scope', function($scope) {
$scope.$watch('input', function(newVal, oldVal){
    //go get some data from a service...
    var reallyNewVal = Date.now();

    $scope.input = reallyNewVal;
});
$scope.$watchCollection('[output]', function(output){
    //watch this, plus some other stuff too, omitted for simplicity
    $scope.output = $scope.input - 1391754634457;
});
}]);

If you want to see a live example, check out this JSfiddle link: http://jsfiddle.net/gC7Zr/

I am asking for help on how to update the $watchCollection function when $scope.input changes due to $watch, without adding $scope.input directly into $watchCollection as it involves a XHR request.

Please share your ideas with me!

EDIT:

For further clarification, here is another example demonstrating what I am trying to achieve: http://jsfiddle.net/n46rj/
Notice how changing B updates C, but changing A does not trigger an update in C. How can I make the $watchCollection 'update' ($digest?) when $watch is triggered?

Answer №1

Because the output is solely dependent on the input, you have the flexibility to modify it within the initial $watch function.

angular.module('testapp', [])
    .controller('MainCtrl', ['$scope', function($scope) {
    $scope.$watch('input', function(newVal, oldVal){
        //retrieve data from a service...
        var reallyNewVal = Date.now();

        $scope.input = reallyNewVal;
        $scope.output = $scope.input - 1391754634457;
    });

    $scope.$watchCollection('[output]', function(output){
        //monitor other variables

    });
}]);

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

Discovering the Modification of a Variable Value in angularJS

Within my HTML markup, I have the following input field: <input id="Search" type="text" placeholder="Search Images.." ng-model="data" ng-keypress="($event.charCode==13)? searchMore() : return"> This input field serves as a search bar for us ...

XML structure is required for showing text area rows

I am looking to extract text area rows and display them in XML format. Below is the code I have tried, which successfully alerts the XML structure. The goal is to display all rows in XML format. Here is the code snippet: $(document).ready(function(){ ...

Tips for retrieving data from a nested Axios request?

Currently, I am working on a series of steps: Phase 1: Initiate an Axios call to verify if the record exists in the database. Phase 2: In case the record does not exist, trigger a POST API call to establish the data and retrieve the POST response. Pha ...

Evolution of the same-origin policy in relation to XMLHttpRequest requests throughout history

About four years ago, I wrote some JavaScript code that included an XMLHttpRequest request. It originally looked like this: xmlhttp.open('GET', 'http://www.example.com/script.php?arg=val&sid=' + Math.random(),true) ; However, sinc ...

Is there a way to display a single Vue component in two separate sub routes simultaneously?

const routes = [ { path: '/', component: LogInView }, { path: '/store', component: Dashboard, children: [ { path: '/products', component: ProductsView, }, ] }, { ...

Use jQuery to display the user input value in real-time

I am in the process of developing a dynamic calculation program to sharpen my jQuery skills, but unfortunately, I'm facing some challenges. I have managed to store values in variables as shown in the code snippet below. <form> Table of: ...

Having trouble resolving a missing dependency warning with the useEffect React Hook in my Next.js app. Any tips on how to fix this

Currently, I'm facing the following warning: Warning: React Hook useEffect has a missing dependency: 'router'. Either include it or remove the dependency array Here is the code snippet from _app.js that seems to be causing this issue: cons ...

A pattern matching formula to eliminate specific characters from the beginning to the end of a string

I am facing an issue with extracting content from a given string: var string = "From: Sarah<br /> Sent: 10 May 2021 09:45:20</br /> To: Alice<br /> Subject: Meeting Reminder<br /><br /> Hi Alice, <br /> Here is a ...

What is the proper way to convert nil to JSON as nil, without representing it as an empty value?

I'm facing an issue in my controller/action where some values turn out to be nil: def my_action @var1 = get_boolean_value || nil @var2 = get_int_value || nil @var3 = get_string_value || nil # there are many more values, any of them might be ...

Hoping for a swift ajax response from the identical function

Even though similar questions have been asked multiple times, I have gone through many of them and still haven't found a solution to my specific issue. I am currently using a Wizard Jquery Plugin that triggers a function onLeaveAStepFunction when a s ...

How to successfully implement ng-show with Html5's <dialog> tags

It's incredible how simple Html5 dialogs are. It feels like they should have been here 15 years ago! I'm having trouble getting ng-show to work with dialogs. Any tips on how to make it happen? <!DOCTYPE html> <html ng-app="project"> ...

Successful AJAX Post request functioning exclusively within the Web Console (Preview)

When a user clicks on an element on the website, I have a simple AJAX request to send the ID of that element. However, the script only works in the Web Console under the Network -> Preview section and this issue occurs across all browsers. Here is the ...

Create a custom Angular directive that allows you to replace tags while inserting the template

I have created a custom directive that can take templates based on the attribute provided. Check out the Plnkr example JS var app = angular.module('app', []); app.directive('sample', function($compile){ var template1 = '<d ...

Tips for preserving data while attempting to access the schema

Attempting to store data from a book that includes author and genre information, referenced in separate files. The issue arises when making the reference in the main schema. Although the book carries details of the book itself, it fails to establish refer ...

Updating model data dynamically in angularjs

I am trying to display a JSON array in a textarea with some slight modifications. The JSON array is stored inside 'list' and $scope.list is connected to a JSON object. Is there a way to dynamically change delimiters from commas to \n in An ...

Stop the occurrence of OpenCPU javascript error pop-up notifications

I'm currently experiencing an error related to CORs during a test deployment of OpenCPU. While I may create a separate question for this issue in the future, for now, I am wondering if it is possible for the deployment to fail without alerting the end ...

Achieving two-way data binding using a Service in AngularJS - Step by step guide

Searching a JSON file, extracting data to create a table, and continuously monitoring for updates to display in real-time is a challenging task. Despite multiple attempts with AngularJS, achieving this has been elusive. Below is the code snippet: app.js ...

Ant Design is incompatible with React JS projects and cannot be effectively utilized

import React from 'react'; import styled from "styled-components"; import {Col, Row} from "antd"; const TitleBig = styled.div` font-family: "Bebas Neue Pro"; font-size: 20px; `; const TitleSmall = styled.div` ...

The React Component is caught in a loop of continuous re-rendering and reloading

Just starting out with React and tackling my first project. Running into a bit of trouble here, so I'm sharing my code for some insight. When users input their search term and hit 'search,' they are redirected from another page to this one. ...

Can anyone please guide me on how to extract the IP address of a specific individual using Node.js?

There's an individual running some kind of exploit scanner on my server. I'm receiving strange requests like: IP ADDRESS: ::ffff:127.0.0.1 www-0 (out): POST /cgi-bin/php5?%2D%64+%61%6C%6C%6F%77%5F%75%72%6C%5F%69%6E%63%6C%75%64%65%3D%6F%6E+%2D%64 ...