Why does AngularJS $watch only execute once?

Why do the codes in the watch only run once? How can I address this issue?

this.$rootScope.$watch('tabType', () => {
    if (this.$rootScope["tabType"] === TabType.Sent) {
        this.$scope.refreshSentList();
    } else if (this.$rootScope["tabType"] === TabType.Archive) {
        this.$scope.refreshArchiveList();
    } else if (this.$rootScope["tabType"] === TabType.Inbox) {
        this.$scope.refreshInboxList();
    } else if (this.$rootScope["tabType"] === TabType.Snooz) {
        this.$scope.refreshSnoozList();
    } else if (this.$rootScope["tabType"] === TabType.Trash) {
        this.$scope.refreshTrashList();
    }
},true);

Answer №1

It seems like the issue may be due to the fact that $watch is unable to locate the element in view when the controller initializes. In order for $watch to function properly, the element must already be present in the view.

My suspicion is that you are using ng-if in the view. The ng-if directive only creates the element when the condition is true.

I have encountered this problem twice before and both times removing ng-if resolved it.

Answer №2

While I see you may be using ES6, this example is actually working on ES5.

Even though you are utilizing ES6, it shouldn't have any impact on how $watch functions.

$scope.$watch('tabType', function (newValue, oldValue) {
    console.log(newValue);
    console.log(oldValue);
});

Additionally, using this at the beginning is not necessary when using $watch.

I hope this information proves to be helpful for you!

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

Adjusting the zoom level in leaflet.js ImageOverlay will cause the marker

Using ImageOverlay to display an image as a map with Leaflet.js, but encountering issues with marker positions shifting when changing the zoom level. Followed instructions from this tutorial, and you can find a code pen example here. // Code for markers ...

Tips for monitoring multiple values in a Vue 3 script setup

Within my code, I currently have a watcher set up like this (inside <script setup>): const form = reactive({ body: '', image: '' }) watch(() => form.image, () => { console.log(form.image) }) I am looking to enh ...

Import failures in Three.js could be attributed to potential issues with Webpack

Please note: I am utilizing create-react-app along with three.js v0.99.0. In my current project, I am faced with the challenge of importing specific modules from three.js to avoid bundling the entire library, which results in a large uncompressed file siz ...

Having difficulty stripping HTML tags from the response JSON

Hello, I am new to AngularJS and facing an issue with parsing JSON data. The JSON response contains HTML format data, with tags like <, BR, etc. When checking the response in a browser, it appears fine; however, on devices such as tablets or mobile phon ...

Error: null does not have the property 'renderView' to be read

My goal is to set up a main page in React.js with two buttons: Option 1 and Option 2. Clicking on Option 1 should redirect the user to the Main1 page, while clicking on Option 2 should lead them to Main2. It seems straightforward, but I am encountering the ...

The jQuery ajax function is failing to return any results

Here is the code snippet I am working with: $("#MainContent_btnSave").click(function () { if (($("#MainContent_txtFunc").val() == "") || ($("#MainContent_cmbLoc").val() == "")) { alert("Please make sure to fill in all required ...

Update AngularJS from version 1.2.6 to Angular 16 in order to resolve the Material issue

Currently, I am working on a project that involves upgrading AngularJS version 1.2.6 to Angular 16. However, I have encountered a significant challenge in understanding the variances between AngularJS material and Angular material. For example, in Angular ...

Using Angular JS to submit forms on a regular basis

My HTML form is set up within an Angular controller with inputs, action, and other elements already defined. The only issue I'm facing is that the form does not have a traditional submit button. Instead, there is a separate button on the page outside ...

Adjust the spacing of a div based on the fluctuating height of another dynamically changing div

Is it possible to dynamically adjust the margin of a div using jQuery or JS? Currently, I have set a margin on a div by calculating the height of a container that includes images. var articleImageHeight = $('.slides_control').height(); $(' ...

Leverage the response data from the first AJAX call as a variable for the second

I have a script that performs two ajax calls - the second one is nested within the success handler of the first. However, I need to utilize the data retrieved in the first success handler as an additional variable to send in the second ajax call, and then ...

Guidelines for creating numerous self-edges within a node-link diagram using D3

Creating a single self-link on a node within a node-link diagram can be accomplished by following the instructions outlined in this resource: D3 Force Layout Self-Linking Node If you need to draw multiple links on the same node, what modifications would y ...

Supplier for a module relying on data received from the server

My current component relies on "MAT_DATE_FORMATS", but I am encountering an issue where the "useValue" needs to be retrieved from the server. Is there a way to make the provider asynchronous in this case? export const MY_FORMATS = { parse: { d ...

Issues encountered transferring data using wp_localize_script

I need help passing PHP data to a JavaScript script in my project. To achieve this, I am utilizing the wp_localize_script function. wp_register_script('googlechart', 'https://www.gstatic.com/charts/loader.js'); wp_register_script(&apos ...

Build a dynamic table by leveraging JSON with the power of JavaScript and HTML

I'm currently working on creating a table where information is stored and updated (not appended) in a JSON file using JavaScript and HTML. The structure of my JSON data looks like this: [{ "A": { "name": "MAK", "height": 170, ...

Having issues with ng-model in AngularJS functionality

Having trouble updating a parent scope within a nested ng-repeat loop. I've been stuck on this issue for the past couple of hours! Here is my nested loop: <div ng-repeat="input in config" style="border: 1px solid #000;"> <div ng-repeat= ...

leveraging an array from a separate JavaScript file within a Next.js page

I am facing a situation where I need to utilize an array from another page within my Next.js project. However, it seems that the information in the array takes time to load, resulting in encountering undefined initially when trying to access it for title a ...

Ensure the div element remains fixed at the top of the page

I created a script to identify when I reach the navigation bar div element and then change its CSS to have a fixed position at the top. However, I am encountering an issue where instead of staying fixed, it jumps back to the beginning of the screen and fli ...

Nuxt.js static pages with relative URLs

I am currently working on developing static pages with Nuxt.js (MPA). After executing the generate command, I noticed that all the URLs in the <nuxt-link> tag start from the root directory, specifically /. For instance, my project structure looks lik ...

Tips for transforming intricate JavaScript arrays into a unified array and iterating through to create a table

I need help combining two arrays that contain objects and reassigning the values in a standard format. Can anyone provide some guidance? Thank you. Here is my current situation: array1 = [{Apple: Ken, Orange: Mary, Melon: Tina, Strawberry: Jessica, Mango ...

Error with decodeURIComponent function in Internet Explorer 8

My widget, loaded as an iframe, requires data about the hosting page. I have UTF-8 strings extracted from a page with Russian text. The page itself has proper HTML5 doctype and meta charset. This is how my code operates: params = "x1=" + encodeURICompone ...