Angular does not seem to be triggering $watch for changes in arrays

Trying to activate a $watch function after a delay in Angular:

Controller Information

.controller('MyCtrl', ['$scope', function ($scope) {
    $scope.chickens = ["Jim", "Joe", "Fred"];
    $scope.chickens.push("Steve");

    setTimeout(function () {
        $scope.chickens.push("Larry");
        $scope.$apply();
    }, 500);
}])

The $watch function is connected in the link function of my directive:

Directive Link Details

link: function (scope, element, attrs) {
    scope.$watch('chickens', function (newChickens, oldChickens) {
        $(element).html('');
        newChickens.forEach(function (chicken) {
            $(element).append($('<li/>', {
                'text': chicken
            }));
        });
    });
}

The $watch only triggers once with the original four elements, not picking up changes after adding the fifth. Tried using $scope.$apply() but no luck.

Check out the Fiddle for an example. Any assistance would be greatly appreciated. Thank you!

Answer №1

To update your directive, you can make the following changes:

link: function (scope, element, attrs) {
    scope.$watch('chickens', function (newChickens, oldChickens) {
        $(element).html('');
        newChickens.forEach(function (chicken) {
            $(element).append($('<li/>', {
                'text': chicken
            }));
        });
    }, true);
}

By setting the third parameter (objectEquality) to true, the watch will compare the entire contents of the array using angular.equals for equality checks between the new and old arrays:

Learn more about angular.equals here!

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

The attempt to execute 'removeChild' on 'Node' was unsuccessful because parameter 1 is not the correct type. Although it did remove the elements from the DOM, it only did so once

It's quite a challenge I'm facing!!! Although there have been similar questions asked before, they were all for specific scenarios. I am currently developing a tictactoe game using the module design pattern. The function below helps me create tw ...

Any tips for filtering an array within an array of objects using the filter method?

I have an array of products and models that I am currently filtering based on 'id' and 'category'. var app = angular.module("myApp", []); app.controller("myCtrl", function($scope) { $scope.products = [{ 'id': 1, ...

Developing tabbed sections in XSLT

Utilizing Angular JS within XSLT, I am aiming to develop a tab-based user interface using XML data. The requirement is to generate multiple links and corresponding div elements based on the number of nodes in the XML. To manage the display of these div ele ...

Stuck with the same icon even after a successful AJAX call

I am currently working on implementing a 'add to my list' function in my web app. The goal is to change the color of an icon when a user clicks on it, after sending the necessary data to the server. Despite successfully sending the data to the s ...

Raycasting in Three.js is ineffective on an object in motion

Working on a project that combines three.js and typescript, I encountered an issue while attempting to color a sphere by raycasting to it. The problem arises when the object moves - the raycast doesn't seem to acknowledge the new position of the objec ...

Using Q to conduct polling asynchronously with promises

I am facing a situation similar to the one discussed in this blog post: Polling with promises. The author explains using promises for polling until a JobID is returned. I intend to implement this using Q. I want to chain promises together but my attempts ...

Incorporating JS objects into HTML: A comprehensive guide

Here is a snippet of code from my JavaScript file: var formStr = "<h5>How many books?:</h5><input type='number' id='bookinput' value='' /><input type='button' value='submit' onclick=& ...

What is the best way to recover accented characters in Express?

Encountering issues with accented characters in my POST request .. I attempted using iconv without success.. Snippet of my code: Edit: ... var bodyString = JSON.stringify(req.body); var options = { host: XXXXX, port: XXX, ...

Capture and transform every alert into a notification

I have implemented Gritter for notifications across my website and am curious if there is an easy method to intercept all alert() messages triggered by scripts using jQuery, and then display the contents of the alert in a Gritter notification. Is there a ...

The Google Pie chart is displaying outside of the designated div area when placed inside a dropdown menu

Encountering an issue with my pie chart rendering outside of its parent div when placed within a dropdown menu. The chart successfully loads after the page is loaded, but only displays correctly if I hover over the dropdown and allow it to load. If I do ...

Locate the specific version of a JavaScript library within compiled JS files

The dist folder houses the results of running npm install. If I don't have access to the original package.json file used during the compilation of the distributable, how can I determine the version of a particular library that was utilized in the ins ...

Configuring Proxy Settings for WebpackDevServer

I need assistance setting up a proxy using WebpackDevServer in my React/Node chrome extension. Currently, my server is running on localhost:4000, and the React frontend is on localhost:5000. When trying to access the route /api/user/ticket using Axios, I ...

Successive vows

I'm trying to retrieve responses from four promises, but I currently have to call each function in sequence one after the other. In my code, you can see that I trigger the next function within the promise callback of the previously called function. H ...

Function that contains a JavaScript reference and observation

I'm experiencing issues with the code below and I'm having trouble figuring out what's causing the problem. function some(){ for (var i=0;i<....;i++) { var oneObject; ...some logic where this object is set oneObject.watch(prop ...

How can I switch the visibility of two A HREF elements by clicking on one of them?

Let me break it down for you in the simplest way possible. First off, there's this <a href="#" id="PAUSE" class="tubular-pause">Pause</a> and then we have a second one <a href="#" id="PLAY" class="tubular-play">Play</a> Al ...

The server is unable to process your request to /graphql

I've encountered an issue while setting up the GraphiQL API. I keep receiving the error message "Cannot POST /graphql" on both the screen and network tab of the console. Despite having similar boilerplate code functioning in another project, I'm ...

What is the process for creating a transparent default color theme in MUI?

I'm looking to make an element's background color the primary main color with some transparency using Material-UI. I've attempted a couple of methods, but unfortunately neither have worked for me. Any suggestions or guidance would be greatly ...

Refresh the view when the URL is modified

Utilizing angularjs alongside ui-router (using the helper stateHelperProvider) to organize views and controllers on the page. Encountering an issue where the views are not updating as expected. The relevant code snippet config.js app.config(function($h ...

What is the best way to reset a dropdown list value in angular?

Is there a way to erase the selected value from an Angular dropdown list using either an x button or a clear button? Thank you. Code <div fxFlex fxLayout="row" formGroupName="people"> <mat-form-field appearance=&quo ...

Tips for sending arguments up in Angular2

I need to supply an argument to a function. <select class="chooseWatchlist" (change)="updateWatchlistTable(item.name)"> <option *ngFor="let item of _items">{{ item.name }}</option> </select> It's crucial for me, as I have ...