"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

When I upgraded my "react-router-dom" from version "5.2.0" to "6.14.0", I encountered a warning stating "No routes matched location"

After updating react-router-dom from version "5.2.0" to "6.14.0", I encountered a warning saying "No routes matched location." Initially, I received an error stating that "<Route> is only meant to be used as a child of <Routes>, not rendered d ...

Is there a way to set an antd checkbox as checked even when its value is falsy within an antd formItem?

I'm currently looking to "invert" the behavior of the antd checkbox component. I am seeking to have the checkbox unchecked when the value/initialValue of the antD formItem is false. Below is my existing code: <FormItem label="Include skills list ...

Jumping over loop iteration following a JavaScript catch block

Currently, I am developing an API that requires making repeated calls to another API (specifically, Quickbooks Online) within a loop. These calls are encapsulated in promises that either resolve or reject based on the response from Quickbooks. Everything f ...

Using socket.io-client in Angular 4: A Step-by-Step Guide

I am attempting to establish a connection between my server side, which is PHP Laravel with Echo WebSocket, and Angular 4. I have attempted to use both ng2-socket-io via npm and laravel-echo via npm, but unfortunately neither were successful. If anyone h ...

Editing XHTML on the fly

Is there a tool available for non-technical individuals to edit hard-coded content in XHTML? I am interested in a solution similar to the integration of Pagelime with jEditable. Currently, my website is static and I am seeking a way for one person to log ...

Press a button to navigate through a series of web pages

Currently, I am working on a website focused on profiles. The challenge I am facing is implementing fixed side buttons (SKIP and ADD) that will cycle through the list of profiles. I understand that I may need to create an array to store all the profiles, ...

"Error message: Antd datepicker is throwing an error stating that date.clone/date.load is not a

I am working on a React app that has a checkbox to disable a datepicker. However, when I use the checkbox to disable it, I am unable to select any date. If I remove the checkbox and its function, there is no error. Currently, the error message I am getting ...

Iterate over the contents within the div tag

I need help with looping through the data in this specific div container. My goal is to extract row by row data from it. <div id="result" runat=server> <div id="gvResult" class="RowGroup"> <div class="Row RowBg" tabindex="99"> ...

Data can be retrieved in a React/Next.js application when a button is clicked, even if the button is located in a separate

Whenever the button is clicked, my function fetches weather data for the current location. I am trying to figure out how to transfer this data from the Location component to the pages/index.tsx. This is where another component will display the data. This ...

Tips for passing a query parameter in a POST request using React.js

I am new to working with ReactJS and I have a question about passing boolean values in the URL as query parameters. Specifically, how can I include a boolean value like in a POST API call? The endpoint for the post call is API_SAMPLE: "/sample", Here is ...

javascriptcode to execute before loading google maps

I am facing an issue with displaying markers on Google Maps. The problem arises when the array with latitude and longitude values is constructed through an Ajax request. Due to the map being loaded before the initialization of the array, I am unable to see ...

Display each new array element on a separate line

let team = [['Sara', 'John', 'Kate']] let newTeam = team.map(function(r) { return r; }) outputs [ [ 'Sara', 'John', 'Kate' ] ] Is there a way to modify it so that each value is r ...

JSON nested error: Cannot read property 'length' of undefined

Having some trouble working with a nested array within a JSON in D3JS, specifically encountering a "property length undefined" error at the line: .attr("d", function(d) { return line(d.points); }). Below is the JSON data structure: [ { "aspectRatio" ...

Exploring AngularJS ng-repeat features for custom attribute settings

I'm currently facing a challenge in removing multiple repetitive divs by utilizing ng-repeat. <!-- I have 21 of these --> <div class="table-row"> <span class="glyphicon glyphicon-wrench"></span> <label>Chlo ...

The utility of commander.js demonstrated in a straightforward example: utilizing a single file argument

Many developers rely on the commander npm package for command-line parsing. I am considering using it as well due to its advanced functionality, such as commands, help, and option flags. For my initial program version, I only require commander to parse ar ...

Exploring Django with Selenium: How to Extract Page Content Using find_element

I have been attempting to extract the text 'Incorrect Credentials' using selenium. Here is what I have experimented with... message_text = self.driver.find_element(By.XPATH, '//*[@id="toast-container"]/div/div[1][@class="ng-binding toast-t ...

Linking chained functions for reuse of code in react-redux through mapStateToProps and mapDispatchToProps

Imagine I have two connected Redux components. The first component is a simple todo loading and display container, with functions passed to connect(): mapStateToProps reads todos from the Redux state, and mapDispatchToProps requests the latest list of todo ...

Tips for achieving expansion of solely the clicked item and not the whole row

I am trying to create a card that contains a cocktail recipe. The card initially displays just the title, and when you click on a button, it should expand to show the full menu and description. The issue I'm facing is that when I click on one element, ...

Troubleshooting problems with anchor-targets in Skrollr

I am experimenting with having divs overlap each other as the page is scrolled using Skrollr. Initially, I was able to achieve the desired effect with two divs. However, when trying to incorporate a third div, only the first and last ones seem to work prop ...

What is the best way to sort and organize JSON data?

Upon successful ajax call, I receive JSON data structured like this: var videolist = [ { "video_id": 0, "video_name": "Guerrero Beard", "timelength": 15 }, { "video_id": 1, "video_name": "Hallie Key", "timelength": 8 }, { ...