Angular $watch not working as expected

I have a specific directive code:

.directive('myDirective', function(){
    'use strict';
    return {
        restrict: 'A'
        , link: function(scope, element, attrs) {
            var count = 0;

            function doSomething() {
                console.log('==== executing ====');
                return { 'count' : count };
            }

            scope.$on('Test', function(event) {
                count += 1;
                console.log('++++broadcast received++++ phase:',  scope.$$phase);
            });

            scope.$watch(doSomething(), function () {
                console.log('-----Seen-----');
            });
        }
    };
})

While broadcasting from a controller in a different scope, the "$on" function is able to receive the broadcast and log the entry successfully. However, the $watch function is not triggering when this happens. The "doSomething" function is not being called at all. The $$phase reports $apply as well.

What mistakes am I making here?

Answer №1

Remember to use scope.$watch(stuff, ...) instead of with parentheses. I learned this from the example code shared by @marck (much appreciated):

  link: function(scope, element, attrs) {
    var count = 0;

    function stuff() {
      console.log('==== calculate ====');
      return {
        'count': count
      };
    }

    scope.$on('Test', function(event) {
      count += 1;
      console.log('count=', count);
    });

    scope.$watch(stuff, function(newValue, oldValue) {
      console.log(newValue, oldValue);
    }, true);

    scope.increaseCountByOne = function() {
      scope.$emit('Test');
    };

  }

Answer №2

$watch is a function in AngularJS that monitors changes to scope variables. When you use $watch(stuff()..., you are invoking the stuff function and allowing Angular to observe the returned value, which in this case is {c:c}.

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

What is the process for converting plain text into an image tag using the methods ".replace()" and ".html()"?

My goal is to customize this particular answer so that it can transform classic BCCode [img]{url}[/img] into an HTML image. In the code snippet provided, I have successfully implemented something similar with [b]text[/b]. However, when attempting to use [i ...

Utilize JavaScript to redirect based on URL parameters with the presence of the "@ symbol"

I need help redirecting to a new page upon button click using a JS function. The URL needs to include an email address parameter. <form> <input type="email" id="mail" placeholder="ENTER YOUR EMAIL ADDRESS" requir ...

Tips for embedding a PHP function within JavaScript code

I am working on enhancing an online application with a translation feature. The application comprises of a frontend coded in HTML and JS, and a backend developed using PHP that is linked to a database. Communication between the frontend and backend occurs ...

Tips for storing HTML form data in a local JSON file without the need for PHP or Node.js dependencies

I'm interested in saving any information panel in an HTML file to a local JSON file. For example, if there are blocks like this: <div class="panel"> <div> <input type="text" name="producttype" id=&q ...

What is the best method for validating multiple fields in a form with Javascript?

I am currently working on validating multiple fields within a form. Although I lack experience in JavaScript, I have managed to piece together a code that is functional for the most part. If all fields are left blank, error messages prompt correctly. Howe ...

The error message popping up reads as follows: "TypeError: _this2.setState cannot

I am encountering an error that I don't quite understand. How can I resolve this issue and why is it occurring in the first place? Although I am receiving the correct response from the API, I am also getting an error immediately after making a call. ...

The responseXML received from an Ajax/POST request is missing only when using Chrome browser

While working on a "simple" JavaScript application, I noticed an unusual behavior. A function in the script sends a request with parameters to a .php page using the traditional Ajax/POST method. function sendRequest(params, doAsync, onSending, onDone) { v ...

Is there a way to append a URL parameter after a link is clicked using Vue.js?

I am currently working on integrating heading links on my website's sidebar that are linked to the main content using scrollspy. This allows users to easily navigate to different sections of the main content by clicking on the corresponding headings i ...

Stop MatDialog instance from destroying

In my application, I have a button that triggers the opening of a component in MatDialog. This component makes API calls and is destroyed when the MatDialog is closed. However, each time I open the MatDialog for the second time by clicking the button agai ...

Aligning a navigation bar with a hamburger menu in the center

I recently implemented a hamburger menu with some cool animations into my site for mobile devices. Now, I am facing the challenge of centering the menu on desktop screens and it's proving to be tricky. The positioning is off, and traditional methods l ...

What causes a statically generated page to appear without any style when transmitted to the client?

After setting up the Next.js official boilerplate with npx create-next-app and opening it in the browser, I observed that the static HTML document lacks styling: https://i.stack.imgur.com/mna6K.png I am concerned about potential FOUC issues. How can I en ...

Sending data from the server to the client in MVC using C#

I sent a token from a View to a function in my HomeController, and now I need to process the token and send back the information to the frontend. I assumed that the resultData returned by the ajax call would be the output of GetMyData, but it turns out it& ...

Trigger functions by clicking or bind click events by calling a function?

I need help comparing two similar code snippets: myFunc(); function myFunc() { var e = document.getElementByClassName("link"), i = e.length; while (i--) { e[i].addEventListener("click", function() { //do stuff for each ...

Checkbox paired with a read-only text column

I have a simple HTML input field with JavaScript functionality, which includes a checkbox. I am trying to write text in the input field when the checkbox is checked, and make the input field read-only when it is not checked. Can anyone provide an example ...

Refreshing the information in the database table

Upon receiving data from the server using ajax, I populate this table: $.each(data, function(i, item) { $('#MyTable tbody').append("<tr>" +"<td>" +data[i].A+ "</td><td>" +data[i].B ...

Limit file selection to images using MUI File Input

I am currently using MUI File Input in React for a file input element. The code I have works well, but I would like to restrict this file input to only accept images. How can I achieve this? Here is what I have done so far: const [locationImg, setLoc ...

Safari browser removes spaces after commas in cookie values

I'm encountering an issue when trying to set a session cookie for storing an Address. It seems that whenever I include a comma followed by a space in the cookie's value, Safari automatically removes the spaces after the commas, causing the format ...

How can we ensure the discord client object is easily accessible within event files?

I'm a beginner with Discord.js and I've been trying to figure out how to allow event and command files to access the main client instance. I want to be able to call client.database in an event file for CRUD operations, but I'm confused on ho ...

Setting the default value to null or 0 in a Select dropdown in Angular 7

There is a select dropdown code that may be hidden in some instances. When the select dropdown is hidden, I want to ensure null or 0 is sent instead of an empty value when saving the form. How can I achieve this? <div class="col-md-4" [hidden]="!cpSe ...

Show only future events using JavaScript and XML

I am facing a challenge with an interactive map that showcases event dates in various regions of the United States. While the map successfully extracts data from an XML document and displays it, I am encountering an issue where events from 2014 are not bei ...