Using Angular's watch function to automatically update variables that are outside the function scope

As a beginner with angularjs, I have encountered an issue that has left me puzzled.

I am wondering how I can ensure that when the watch function runs for the second time (on init), the testValue is "changed".

<div ng-controller="MyCtrl"></div>

Here is the javascript code :

var myApp = angular.module('myApp',[]); 
function MyCtrl ($scope) {
  var testValue = null;
  $scope.watchMe = null;        
  $scope.$watch('watchMe', function () {
    console.log('testValue is', testValue);        
    if(testValue !== null){
        console.log('I want to do something different the 2nd time this code runs - but I never get in here...');
    }
    testValue ="changed";
  });
};

For reference, you can view the code on this jsfiddle example.

Thank you for your assistance.

Answer №1

Your approach to using watch seems a bit off

Watch should be used to respond to changes in a model and trigger additional actions

You need to designate a model as the watch expression and monitor it for any changes so that the watch function is activated

<div ng-app="myApp" ng-controller="MyCtrl">
  <input type="text" ng-model="name" placeholder="Enter your name">
  <p>{{greeting}}</p>
</div>

and here's the JavaScript code:

var myApp = angular.module('myApp',[]); 
function MyCtrl($scope) {
  $scope.name = "";

  $scope.$watch("name", function(newValue, oldValue) {
    if ($scope.name.length > 0) {
      $scope.greeting = "Greetings " + $scope.name;
         console.log("change detected: " + newValue);
    }
  });
}

Answer №2

After some investigation, it was determined that the issue did not lie within the watch itself, but rather in the controller being called twice. It is still unclear why this occurs within the fiddle, but a log was added to pinpoint this as the root cause.

To clarify further - the variable testValue continues to return null because the controller function runs again after the watch function, causing it to overwrite var testValue.

There could be many reasons for this behavior - in my situation, I had assigned the controller to an element, as showcased in the fiddle.

<div ng-controller="MyCtrl"></div>

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

Attempting to prevent the insertion of duplicate values more than once

Is there a way to prevent duplicate values from being submitted in my simple site? Currently, I have implemented a function that allows users to input a name and a mark. However, if the same values (name & mark) are entered, I want to notify the user and ...

What is the best way to connect objects that have been separated?

Looking for a way to reattach my detached objects and wondering how to replace the function that currently only triggers an alert. Any suggestions or help is appreciated. http://jsfiddle.net/jy2Zj/ In addition, I have another question - is there a method ...

What location is optimal for storing ng-templates within an Angular/Django single-page application?

My project involves using Django and AngularJS to create a single-page application. I have numerous ng-templates structured like this: <script type="text/ng-template" id="item.html"> // content </script> Currently, all these templates are l ...

Preventing users from selecting both future and current dates in a Bootstrap datepicker: A Step-by-Step Guide

Issue Description: I am working on a project using React JS and have implemented the bootstrap datepicker. I have set the input type to "date" for the date of birth field, but I need to restrict users from selecting current or future dates. How can I achie ...

Persisted state in Vuex fails to retain data after the page is refreshed

I recently added persisted state to my Vue application using the command npm install --save vuex-persistedstate. After that, I configured my Vuex store.js file in the following way: import Vue from 'vue' import Vuex from 'vuex' import ...

Executing Continuous Process using Node.js

I am currently working on a server project that involves streaming webcam footage and other functionalities. Everything is set up within my node.js server, with an HTML page that includes a select drop-down menu linked to a JavaScript function via socket.i ...

Force restart broken socket within Node.js program using Socket.IO programmatically

I have a simple one-to-one client and server Node.js based application. The Node.js is running on Linux (Intel Edison). I am attempting to automatically reboot the Linux server whenever the socket connection is broken. Is this achievable? Below is my unco ...

Updating the background color and adjusting the main content background on a WordPress site

After spending nearly an hour searching for a solution to my problem with no luck, I've come to the conclusion that most YouTube videos are not helpful at all. My website is built on WordPress and I am attempting to change the background color and mai ...

What is the best way to adjust the translateX value upon clicking a button?

I'm exploring react for the first time. I want to create a button that will change the translateX value by 1170px when clicked, but I am confused about how the onClick attribute works in reactjs. Below is the code snippet: function Slideshow() { co ...

Steps to Implement CSS Background Change on Click Event

Take a look at this JSFiddle link. In the code, you will find two divs called step-wrapper, each containing three divs named step-box. When you click on a step-box, its background color changes to yellow. I have included a reset button. What I want is for ...

Strange sequence of results coming from Vue.js

methods: { ShowWindow: function(QueryID) { this.$data.ID = QueryID; if(this.GetData()) { console.log("asdasd") } document.querySelector("#EditWindow").style.visibility = "visi ...

The state update was not completed before another update had already begun

Check out this object I have: { "Item1": "books", "Item2": "pen", "Item3": "desk", } I receive it in my react application through a rest API. const Items: React.FC = () => { interface DataType { [key: string]: string; } const [info, ...

Filtering data from a REST API in AngularJS according to the value entered in a textbox

Alright, here’s the setup: angular.module('myApp.services', ['ngResource']) .factory('STLineup', function($resource){ return $resource('http://someapi.com?filters=location.eventInstance.slug:Slug,artists.t ...

Learn the process of synchronously loading forms and data in Angular

Looking to synchronize the loading of data and form... Let's start by reviewing the code: ngOnInit() { if (this.data.fromCalendar) { this.singleTraining(); } }, 200); this.formControl(); } formControl() { this.gib ...

Tips on updating time zone settings in a browser using React JS or JavaScript

I am currently facing a requirement where I need to adjust the application's time based on an environment variable. The entire application should operate using the timezone specified in the configuration file. For instance, if the designated timezone ...

Synchronously retrieving JSON data from a URL using JavaScript

I'm currently working on extracting the title of a YouTube video using jQuery to parse JSON. The issue I am facing is that it works asynchronously, resulting in the answer being displayed after the page has already loaded. Here's the current resu ...

Having trouble retrieving information from the JSON data received from the Google Place Search API

I'm encountering an issue with accessing data from the Google Place Search API. I've provided my code below for reference. getData = (keyword, location, country) => { let dataURI = `${URI}${keyword}+${location}+${country}${API}`; var ...

What is the best way to save data in order to effectively showcase a collection of images that together form a single entity in a game

Apologies for the unclear title, I struggled to find the right words. Recently, I delved into the world of 2D game development and was amazed by the capabilities of HTML5's Canvas element. Currently, I am working on my first basic project to grasp th ...

How can service properties be updated in AngularJS without moving the logic outside of the controller?

Here is an example of what a standard service might look like: (function() { angular.module('module').service('SomeService', SomeService); SomeService.$inject = ['$http']; function SomeService($http) { v ...

The Select2 ajax process runs twice

I am encountering an issue with a script I have that retrieves data from the backend to populate a select2 dropdown. The problem is that the ajax call is being triggered twice every time, which is not the desired behavior. I'm unsure of what mistake I ...