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

Which is better for scrolling in Angular 2+: using HostListener or window.pageYOffset?

Which syntax is best for maximizing performance in Angular 2+? Is it necessary to use HostListener, or is it simpler to obtain the scroll position using the onscroll window event and pageYOffset? @HostListener('window:scroll', ['$event&ap ...

Exploring the depths of a multidimensional dictionary within AngularJS

I am currently working on a project using AngularJS. The data I have is in the form of JSON: { "leagues":{ "aLeague":{ "country":"aCountry", "matchs":{ "aUniqueID1":{ "date":"2014-09-07 13:00:00", "guest_play ...

The jQuery target is not able to locate the specified element

Why does this code snippet work in one case: jQuery(this).closest("li").find("p").text(); But when enclosed within a function, it fails to produce the desired result: jQuery.each(words, function(i, v) { jQuery(this).closest("li").find("p").text(); } ...

Implementing a method to pass total value to the <td> tag in angular JS using controller

I am having trouble calculating the total IR for each table cell. Despite my efforts, the function is not working as expected and I can't figure out why. $scope.getTotalb = function () { var totalb = 0; for (var i = 0; i < $scope ...

Assign properties to a component from an object

I'm working on connecting React Components to Objects by passing imported Components as Props. const [showComponent, setShowComponent] = useState([ { cId: 1, componentName: <ContactDialogAddresses />, title: 'Address', render: true ...

Navigating through pages using Nuxt UI-pagination

Having some trouble with setting up the pagination feature from Nuxt UI. Despite trying to research through documentation and videos, I can't seem to figure out how to connect my data to the component. <template> <div> ...

Using AngularJS within XSLT: Unrecognized prefix 'true' encountered

I have a button that uses ng-repeat. Inside this button, I am applying an active class based on the default product. <button type="button" ng-model="selectedProductGroup" ng-repeat="item in pgroup |unique: 'Product' track by $index" ng-click= ...

Creating a Vue application utilizing a function with an unspecified purpose

Looking to create an app with a function that is currently undefined. On the production server, there is a function called __doPostBack which I am calling from my Vue app like this: getLabel(templateName) { __doPostBack(templateName, ""); } Afte ...

Storing deeply nested arrays of objects with Mongoose leads to MongoDB storing empty objects

Here's the issue I'm facing: I am trying to save nested objects with mongoose in mongodb, but when I save them, the nested objects end up empty. I have attempted various solutions found online, such as pushing objects and populating, but none o ...

Is there a way to transform a personalized jquery event listener into an angularjs listener?

A custom event listener was created using jQuery for an angularjs component. The event is triggered by a non-angularjs library. $( "#myDiv" ).on( "CornerstoneImageRendered", function(e) { // buisness logic }); The element myDiv is a div that belongs t ...

What are the best practices for utilizing intro.js effectively on mobile devices?

Description When using introjs on mobile devices with a screen width of less than 600px, the tooltip ends up covering the element. When I hold the device horizontally, the tooltip adjusts its position accordingly. I attempted to apply custom CSS to the too ...

What is the method to alter the color of an SVG source within an image tag?

I am currently working on a component that involves changing the color of an SVG icon from black to white when a color prop is given. export class CategoryIconComponent extends React.Component { static displayName = 'CategoryIcon'; state = ...

Attempting to utilize the LLL algorithm as described on Wikipedia has led to encountering significant challenges

I'm struggling with determining whether my issue stems from programming or understanding the LLL algorithm mentioned on Wikipedia. To gain a better understanding of the LLL algorithm, I attempted to implement it following the instructions outlined on ...

Is there a way to assign a dynamic value to an input just once, and then retain the updated value without it changing again

During a for loop, I have an input element (type number) that needs its value modified by decrease and increase buttons: <div class="s-featured-list__item s-featured-list__item--expandable" v-for="(item, itemIndex) in category.items" ...

Acquiring the content of elements contained within a div container

On a webpage, I have included multiple div elements with unique IDs and the following structure: <div class="alert alert-info" id="1"> <p><b><span class="adName">Name</span></b><br> ...

Using Regex with JavaScript while ignoring letter case

I am trying to extract a query string from my URL using JavaScript, and I need to perform a case-insensitive comparison for the query string name. In order to achieve this, here is the code snippet that I am currently using: var results = new RegExp(&apos ...

Generate interactive tables using data from an XML file

Hello, I'm in the process of generating tables from an XML file using Node.js with the Express framework. I am utilizing npm modules xmldom and xmldoc for this task. The objective is to present these data tables on an ejs page. Here is the structure ...

Tips for removing an element from an array in a JSON structure using its unique identifier

This problem seems to be fairly straightforward but it’s giving me some trouble. Here is the JSON structure I'm working with: "playlists" : [ { "id" : "1", "owner_id" : "2", ...

Generating numerous responses in Node (sails js) from a solitary function

Currently, I am facing an issue while developing a web application using AngularJS and Sails. The problem arises in my application's menu section where different count values are supposed to be displayed from the database. When I try to retrieve this ...

Issue with content overlapping when hamburger icon is tapped on mobile device

When the hamburger menu is pressed on smaller screens, I want my navbar to cover the entire screen. To achieve this, I included the .push class in my code (see the jQuery and CSS) to trigger when the .navbar-toggle-icon is pushed. However, after implemen ...