"Controller's $watch function fails to trigger when new items are added to an array within a directive

Within my code, I have established a two-way binding variable called publish.selected_tags that connects a directive with a controller.

To monitor changes in this variable, I implemented a $watch function within my controller:

$scope.$watch('publish.selected_tags', function(new_val, old_val) {
    console.log(new_val); //print new value
})

A dilemma has arisen where the triggering of the $watch does not occur when an item is added to the selected_tags array:

return {
    scope: {
        selected_tags: '='
    },
    link: function(scope, element, attrs) {
        scope.selected_tags.push('item') //controller's watch remains inactive
    }
}

Remarkably, however, once the selected_tags is assigned as an array, the controller's $watch functions correctly:

return {
    scope: {
        selected_tags: '='
    },
    link: function(scope, element, attrs) {
        scope.selected_tags = ['item'] //controller's watch successfully triggered!
    }
}

This inconsistency raises questions. Why does the $watch not activate when pushing elements? How can this be resolved?

Answer №1

$watch allows you to monitor individual properties within the scope. To track changes in a collection, you can utilize $watchCollection for shallow monitoring or

$watch('publish.selected_tags', function(newVal, oldVal){}, true)
for deep observation.

Answer №2

In my opinion, it would be beneficial to utilize $watchCollection() in order to monitor changes within an array. As opposed to $watch(), which triggers when the expression value changes rather than on property adjustments inside the object under observation, if I am correct.

For more information, refer to https://code.angularjs.org/1.1.4/docs/api/ng.$rootScope.Scope#$watchCollection

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

Is utilizing React function components the most effective solution for this problem?

export default function loginUserUsing(loginType: string) { const [state, setState] = useState(loginType); function login() { // body of the login function } function oauth() { // body of the oauth function login(); ...

Webpack is ejected from watch mode

Currently, I am in the process of learning React and have decided to use webpack alongside it. However, I seem to be facing an issue with webpack when it comes to the watch mode. It builds the files once but then halts. The console output reflects the foll ...

Troubleshooting the issues with implementing cross-browser jscrollpane functionality

Hey there! I've been exploring this tool to customize the default scroll-bar, and here's a fiddle showcasing my experimentation. In the fiddle, I've included the following code snippet <div class="scroll-pane horizontal-only">(located ...

Comparing the functionalities of C#, Python, and JavaScript, including rounding methods

There seems to be a difference in how decimal numbers are rounded in C# or Python compared to Javascript. I came across a solution for banker's rounding on Stack Overflow, but it doesn't work as expected in my scenario and leads to discrepancies ...

Send an API call for every item in a given list

There is a function that I am working with: updateCustomers = (input) => { //let urls = input; let urls = [{ name: "localhost:8081", url: "http://localhost:8081" }, { name: "localhost:8082", url: "http://localhost:8081" }, { ...

Error: Unable to locate module './clock' in the directory '/home/n/MyWork/my-app/src'

Upon attempting to start up the project, I encountered an error message stating: "Module not found: Can't resolve './clock' in '/home/n/MyWork/my-app/src'" The structure of the project is as follows: My-app --node-modules --public ...

What is the best way to show the initial image within every div that has the class name .className?

I am looking to only show the first image in each div with the class name "className." This... <div class="className"> <p>Yo yo yo</p> <p><img src="snoop.jpg" /></p> </div> <div class="className"> Hel ...

What steps can be taken in Next.js to display a 404 page when data is not retrieved from the Wordpress admin?

I am working with JSON data that looks like this: [ { "taxonomy_slug": "product_cat", "taxonomy_name": "Categories", "frontend_slug": "product-category" }, { ...

Resolving Node.js Absolute Module Paths with TypeScript

Currently, I am facing an issue where the modules need to be resolved based on the baseUrl so that the output code is compatible with node.js. Here is my file path: src/server/index.ts import express = require('express'); import {port, database ...

Utilizing Angular JS to parse JSON data and showcase it in various tables

Just diving into Angular JS and looking for some guidance. Can someone show me how to parse and showcase JSON Data in separate tables using Angular JS? [ { "id": 0, "isActive": false, "balance": 1025.00, "picture": "htt ...

PHP form submission upon conditions being satisfied

I am not utilizing Javascript as it is disabled in my current environment. Here is the code that I would like you to review. I am attempting to use PHP to replicate the functionality of Javascript or jQuery's simple : document.form2.submit() <div ...

Tips for enabling the background div to scroll while the modal is being displayed

When the shadow view modal pops up, I still want my background div to remain scrollable. Is there a way to achieve this? .main-wrapper { display: flex; flex-direction: column; flex-wrap: nowrap; width: 100%; height: 100%; overflow-x: hidden; ...

Can we expand the capabilities of a ThreeJS object in any way?

In my ThreeJS project, I am implementing an interactive feature where users can click on cubes that behave differently when clicked, such as having different color animations. To achieve this, I plan to create extension classes for the THREE.Mesh object a ...

Retrieve the text content of a datalist option by accessing the label with jQuery

Utilizing data from a Json, I am populating a data-list in html. The options are added to the data-list with both value and label text. Upon clicking an option, I aim to insert both the value and text into a form text field. While accessing the option&apo ...

The alert feature does not seem to be functioning properly when displaying error messages

// Issue: Alert is not working on error message. I intend to only display up to four issues, after that it should not work. success: function(msg, String, jqXHR) { window.location = 'home.html'; $("#result").html(msg, String, jqX ...

displaying li tag depending on the index value within angularjs

I have an HTML structure similar to the following: <div class="main"> <ul> <li ng-repeat='save in saves'> <h3>{{save.name}}</h3> <div > <ul> ...

Is it possible to customize the MongoDB Collection before loading the web application by fetching data asynchronously using Promises?

I am currently working with MongoDB and NodeJS, trying to preload my Collection customers every time the site is loaded. The process involves emptying the collection, populating it with empty Documents, and then replacing them with real data fetched from a ...

Utilize Node.js driver to export a Mongo collection into a JSON file

How can I export a MongoDB collection to a JSON format using the Node.js driver and fs.writeFile? ...

What could be the issue causing Vue to not start up properly?

I have been working on a Rails application and have integrated some Vue components into the pages. The components range from simple dynamic lists to more complex implementations with nested components. Let me walk you through how it all functions with som ...

How to Use Conditional In-Line CSS for Internet Explorer and Other Browsers

After inspecting the source code for this website, I noticed a cool feature where the page changes based on your scrolling position. It creates a visually appealing effect. Upon further examination of the source in FireFox, I observed the use of -webkit-t ...