Suggestions for rearranging the sequence of watchers in AngularJS?

After creating a controller and directive with local scope, I added a watcher on a scope variable in the postLink method and implemented $interval to change the variable. Additionally, I included a watcher on the binded variable in the controller.

console.clear();
var myApp = angular.module('myApp', []);

myApp.controller('MainCtrl', ['$scope',
  function($scope) {

       $scope.$watch(function() {
      return $scope.ctrlVar;
    }, function(newValue) {
      console.log('WATCHER TWO: newValue = ', newValue);
    }, true);

  }
]);

myApp.directive('testDirective', 
 ['$interval', function($interval) {
    return {
      scope: {
        date: '=dateModel'
      },
      template: "<input type='text' value='{{date}}' />",
      restrict: 'E',
      link: function postLink(scope, element) {
        console.log('link');
        var i = 1;
        $interval(function() {
              scope.date = i++;

        }, 1000);

          scope.$watch('date', function(){
          console.log('WATCHER ONE: newValue = ', scope.date);
        });

      }
    };
  }]
);

html:

<body ng-app="myApp">
  <div ng-controller="MainCtrl">
    <test-directive date-model="ctrlVar"></test-directive>
  </div>

  <script src="script.js"></script>
</body>

</html>

The order of invoking watch listeners is as follows:

WATCHER IN CONTROLLER: newValue =  undefined
script.js:32 WATCHER IN DIRECTIVE: newValue =  undefined
script.js:32 WATCHER IN DIRECTIVE: newValue =  1
script.js:10 WATCHER IN CONTROLLER: newValue =  1
script.js:32 WATCHER IN DIRECTIVE: newValue =  2
script.js:10 WATCHER IN CONTROLLER: newValue =  2

In some cases, the behavior of the watchers can be different, especially when dealing with more complex production code. Have you experienced this issue before?

If you want to manage the order of watch listeners, check out this example http://plnkr.co/edit/QzeZar?p=preview

Answer №1

I concur with @DRobinson's suggestion. If you really need to alter the order of the watchers, one workaround could be using timeouts to establish a sort of 'priority' for your watchers. While I am unaware of any method to modify the watchers after they have been registered, delaying their registration might be an option.

myApp.controller('MainCtrl', ['$scope', '$timeout', function ($scope, $timeout) {
    $timeout(function () {
        $scope.$watch(function () {
            return $scope.ctrlVar;
        }, function (newValue) {
            console.log('WATCHER TWO: newValue = ', newValue);
        }, true);
   }, 10);

}]);

A demonstration in this fiddle illustrates that watcher two triggers AFTER watcher one initially. http://jsfiddle.net/qj7gn5x4/1/

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

Troubleshooting Vue.js data binding problems

Utilizing HTML targeting with data binding <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <div class="row" v-for="test in tests"> <div class="col-12"> <router-link tag="a" :to="{ name: ...

Guide on creating my inaugural HTML embeddable widget?

A client recently requested me to create a JavaScript (MooTools)/HTML/CSS/PHP based game as a deployable widget. This will be my first time developing a widget, so I am seeking advice and insights to help me navigate any potential challenges from experie ...

Retrieve data from API using ReactJS and passing parameters to the request

I am trying to retrieve information from the API based on the data I am sending, but encountering two issues: Initially, I hardcoded the information being sent to the API (year and term) as it should return the data I am trying to store, however, it is ...

Creating dynamic pie charts with animated effects using JavaScript

Looking to develop an interactive pie chart using JavaScript, I delved into some research and stumbled upon the Google Charts API. However, my primary apprehension lies in the fact that the data is transmitted to Google's server for generating the ch ...

React: Premature exit, Fewer hooks executed than anticipated

I'm currently working on a chrome extension project where I'm trying to update an object based on a change in the current tab. However, I keep encountering an error that says I've rendered fewer hooks than expected. How can I resolve this is ...

Step-by-step guide to performing an AJAX request in JavaScript while using Ubuntu

My current setup involves using a JavaScript file in conjunction with NodeJS to execute AJAX calls. To accomplish this, I have installed and imported jQuery as demonstrated below: var http = require("http"); $ = require("jquery"); test(); funct ...

What's causing nested promises to fail in my code?

Despite never having attempted nested promises before, I decided to give it a try based on what I've read and learned online. However, when implementing nested promises in my code, things didn't go as expected: APIService.getData(Config + header ...

"Encountering issues with createReadStream function when handling large files, performance is significantly

Currently, I am utilizing the DropBox API for file uploads. The process involves several steps: Begin by uploading the file from a form to a local directory on the server. Read the file from the local directory using fs.createReadStream. Transfer the fil ...

Sending a Django form using AJAX and jQuery: A step-by-step guide

After researching various tutorials on django AJAX forms, I've found that each one offers a different method, but none of them seem simple. Being new to AJAX, I'm feeling a bit confused by the complexity involved. In my specific case, I have a m ...

Dynamic inheritance in Node.js based on the version being used

Why does the code provided only function correctly in Node.js versions 5.x and 6.x, but not in versions 4.x and older? Is there a way to modify the code so that it can work across Node.js versions 0.10.x - 6.x? 'use strict'; var util = require ...

What is the best way to display two array lists in JSON format and view them in data table rows using ASP.NET MVC?

There are two array lists, RoleList and EmpList. How can I return both arrays in JSON format and display them in rows on a data table? In order to return both arrays, you can use the following code snippet: return Json(EmpList,RoleList, JsonRequestBehavio ...

Maximizing Database Connectivity in Azure Functions with Javascript

I'm having trouble finding clear guidelines on how to handle database connections (specifically MongoDB) in an Azure function written in JavaScript. According to a Microsoft document linked below, it's advised not to create a new connection for ...

What could be the reason for AngularJS directives (such as attributes) appearing as "invalid" in WebStorm 8?

Just recently, I downloaded and installed WebStorm 8 onto my computer. I have been working on some AngularJS projects and have encountered a frustrating issue. The AngularJS plugin appears to be only partially functioning - when I type ng- in the code edit ...

Exploring the World of 3D Rotation with Three.js

I currently have 2 mesh objects - the Anchor and the Rod. The Anchor rotates around the z-axis, as shown in the image. The Rod is designed to only move backward and forwards. You can view the image here: . However, I am struggling to determine the matrix ...

Retrieving the output from a function in Angular

Below is the scope function present in my controller: $scope.getStaff = function (request, response) { var a = []; if ($scope.staff !== null) { // All terms must be contained a = $scope.staff; var terms = request.term.toLo ...

How can I extract a specific value from an array in a JSON object by sorting it?

As someone who is relatively new to JSON and APIs, I am currently working on a project involving an API that returns values in an array structure. Here is an example of the data: { id: 0, text: "one" } { id: 1, text: "two" } ...

What is the best way to dynamically update the selected option in a dropdown menu within a Rails application using a variable?

Working on a project that involves a select drop-down menu containing a list of currencies. Want to enhance user experience by automatically selecting the default value in the dropdown based on the user's country (will be utilizing the geoip gem). To ...

Is your toggle() function failing to work on dynamically loaded ajax content?

$('.slideArrow').toggle(function (event) { //some code }, function (event) { //some code }); This code functions correctly for content loaded during the page load process. However, it fails to work for content loaded via ajax requests. The ...

Guide to retrieving the data type of a List Column using SharePoint's REST API

I am currently attempting to determine the type of columns in my SharePoint list so that I can accurately populate a form with the appropriate field types. During my research, I stumbled upon this informative article in the documentation which discusses ac ...

Do NodeJS and Express require sanitizing the request body for post requests to prevent cross-site scripting (XSS) attacks?

There is a website I have where users can input data into fields and submit it. Once submitted, the information is sent to my server through a POST request and saved in the database. However, this user-generated content is also returned to the front-end f ...