Learn how to access a variable within the Watch function using a directive in Angular framework

I'm new to Angular and encountering some issues with the watch function. I am trying to track changes in a variable inside a controller, and once the value of this variable changes, I want to pass that updated value to a directive.

Below is the code for the watch function:

$scope.$watch("comboDetail", function(newValue, oldValue) {
  $scope.overlayProductCard = $scope.comboDetail.collectionCd;
  console.log("$scope.overlayProductCardWithinWatch", $scope.overlayProductCard);
}

Here's a snippet of my directive code: (trimmed for better readability)

return {
scope: {
      productCard: '='
    },
    restrict: 'E',
    templateUrl: appVersionFactory.getViewBaseUrl() + '/assets/partials/tv/tv-overlay-link.html',
    replace: true,
    link: function($scope, iElm, iAttrs, controller) {
      console.log("$scope.productCard", $scope.productCard);

  };

However, when I try to access $scope.productCard in the directive, it returns undefined. On the other hand,

$scope.overlayProductCardWithinWatch
gives me the correct data. How can I retrieve this data in the directive?

Answer №1

Imagine having a directive like

<example param="controllerParam"></example>
with the template <div>{{param}}</div>. If I update the value of controllerParam in the controller, the directive will automatically reflect this change without needing any additional code to watch for it. However, if I want to log the new value in the directive every time it changes, I would need to set up a watch function within the directive.

The link function is only executed once per element, so you will only log the initial value of the variable at that moment.

Answer №2

Give this a try:

link: function($scope, iElm, iAttrs, controller) {
  scope.$watch('productCard', function (newValue) {
    console.log("$scope.productCard", newValue);
  })
};

Prior to that, make sure to include productCard in your element tag within the HTML, for example:

data-product-card="overlayProductCard"

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 there a simpler method for transforming JSON into CSV format?

I'm dealing with a JSON string that's a bit messy: [[{ "Table":{ "Properties":{ "name":"ABOUT", "uniqueConstraints":"{}" }, "Attributes": [{ "name":"NAME", "unique":"tru ...

The Zustand store does not reflect changes when the URL is updated

I have a Zustand store connected to the URL. See the code snippet provided below. import { create } from "zustand"; import { persist, StateStorage, createJSONStorage } from "zustand/middleware"; const pathStorage: StateStorage = { ge ...

Enhance the aesthetic appeal of the imported React component with added style

I need assistance with applying different styles to an imported 'notification' component within my header component. The notification component has its own CSS style, but I want to display it in the header component with unique styling. How can I ...

Handlebars template engine does not support query parameters

Below is the code snippet I am working with: app.get("/editar-equipo?:id", (req, res) => { const equipos = obtenerEquipos() let equipoSeleccionado for(let i = 0; i < equipos.length; i++){ if(equipos[i].numeroId === ...

Where should Babel and Webpack be placed in your package.json file - under devDependencies or Dependencies?

I'm a beginner when it comes to npm and I have doubts on what should be included in dependencies as opposed to devDependencies. I understand that testing libraries belong in dev, but what about tools like babel and webpack? Should they also be categor ...

What is the best way to search for all results in MongoDB that have x appearing in any property?

Is it possible to search for all pictures in the mongoose framework with node and express that contain a specific parameter, regardless of which property holds that parameter? For example: If I enter "John Snow" in the search bar, I want to see all pictur ...

Tips for Loading a Selected Option from an Ajax Call in Angular JS on Page Load

How do I automatically set the selected option from an ajax call when the page loads? I am fetching zones using an ajax call and I want to trigger the change function of the zones on page load in order to set the selected option of the cities select box. ...

What is the best way to highlight a specific city on a map by placing a circle around it?

I am currently developing a project that involves creating a circle around the location of an item on a Google Map. In the code snippet below, when the show tab is clicked, it should display a circle around the item's location on the map: <div cla ...

The ng-click event in AngularJS does not function as expected when nested within another ng-repeat loop

I am facing an issue with ng-click in my Angular application (version 1.0.4). The first ng-click works fine, but the second one does not. <div class="menu-group" ng-repeat="module in modules"> <div ng-click="toggle($event, $parent)" ...

Navigating through Sails.js: A comprehensive guide on executing test cases

Being a beginner in sails, node, and js, I may be missing out on some obvious steps. My environment includes sails 0.10.5 and node 0.10.33. Although the sails.js documentation covers tests in , it does not provide instructions on how to actually execute ...

Turn off scrolling for the body content without removing the scrollbar visibility

Whenever I click a thumbnail, a div overlay box appears on top: .view-overlay { display:none; position:fixed; top:0; left:0; right:0; bottom:0; overflow-y:scroll; background-color:rgba(0,0,0,0.7); z-index:999; } Some browsers with non-f ...

Ways to stop the default action in a confirm dialog while using Angular JS

Within my save function, I have the following: $scope.saveData = function () { if (confirm("Are you sure you want to save") === false) { return } // do saving When using the above code and clicking "yes," I encounter an error. Interestin ...

Unable to integrate npm package into Nuxt.js, encountering issues with [vue-star-rating] plugin

Just starting with nuxt js and running into issues when trying to add npm packages. Below are my attempts. star-raing.js import Vue from 'vue' import StarsRatings from 'vue-star-rating' Vue.use(StarsRatings) nuxt.config.js plugi ...

What is the best way to adjust the specific scope of every element generated by ng-repeat within a directive?

Attempting to simplify tables in Angular, I am working on a directive. My goal is for the user to only need to provide the list object and the formatting of each list element in the HTML, using the my-table tag as shown below... <h3>My Table</h3& ...

What is causing myInterval to not be cleared properly?

const homeButton = document.getElementById('home'); window.myInterval = 0; const showHome = () => { console.log('showHome'); window.myInterval = setInterval(wait, 400) } const wait = () => { console.log('wait'); ...

AngularJS's ng-repeat feature is not properly re-embedding tweets

In my project, I am utilizing angularjs to showcase tweets. The implementation involves using ng-repeat alongside a filter that is directly linked to the state of a checkbox. When the checkbox is checked, the filter returns all the tweets (the default beha ...

Tips for transferring date values in an ajax request to a web application handler

I am currently working on plotting a graph between two dates using Google Charts. My goal is to send date values to the controller, which is implemented with webapp2. However, I am facing difficulties in figuring out how to send date values to the controll ...

What is the method to obtain the content height of individual pages in Android, with or without the use of JavaScript?

I am facing an issue while trying to retrieve the content height of each webpage consecutively. When I load pages separately, I can successfully get the height of each page. However, when I attempt to fetch the content height continuously for webpages in a ...

Is there a way to close the menu in react by clicking anywhere on the

Presently, I have a solution to close my topbar menu that involves clicking the menu icon. However, this method is not satisfactory because it only closes the menu when the icon is clicked. I am looking for a way to make the menu close when any area of th ...

Exploring the implementation of constructors and classes in JavaScript

I have a task to create a class named ShoppingCart with specific instructions: The class should have a constructor that initializes the total attribute to zero and creates an empty dictionary attribute called items. There should be a method named add_ite ...