Trouble with Directive - the watch function isn't functioning as expected

After spending countless hours and trying almost everything, I can't seem to get it to work...

I have an Angular directive that calls another Angular directive. I need to handle events in the child directive. So my child directive looks like:

           restrict: 'E',
           replace: true,
           scope: {
               testResult: "=",

And in the parent directive I have:

<my-search-directive test-result="newTest"></my-search-directive>

To handle changes in testResult, in the parent directive I have this watch:

  $scope.$watch('newTest', function (newVal, oldVal) {
      alert('test ' + newVal + ' ' + oldVal);
  }, true);

It only fires once in the beginning and newVal and oldVal are undefined... If I use a service instead of the 'master' directive, it works (passing parentScope and using it for watch).

Initially, newTest was returning a complex object and I thought that could be the problem, but it's not because it now works with a simple string as well.

I tried using $watchCollection, but it's also not working... I need this exact scenario - a directive within a directive - and I can't figure out how it can work?

EDIT 1 :

myApp.directive('parentDirective', [
    "$log", function ($log) {

        return {
            scope: {
                getQueriesUrl: "=",
                isFullyQualified: "=",
                isMainTabs: "=",
                model: "=",
                crudUrls: "=",
                callBackFunction: "&",
                callback: "&",
                newTestResult: "@"
            },
            restrict: 'A',
            replace: true,
            controller: function ($scope) 
{
myActions.push('<div><my-search-directive test-result="newTestResult"></my-search-directive></div>');
}

That is my 'parent directive', so I need to track changes of test-result. As @Walfrat mentioned, I added the newTestResult variable, but it still doesn't work...

Answer №1

Let's start by addressing the fact that you are not utilizing directive within a directive.

Here, you have implemented a directive with two-way binding.

Given that your scope is connected to data, it is important to monitor the changes in testResult as specified in your scope{} block. If $watch is not effective, consider using watchCollection instead for better results.

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

How can you target a specific data-target button while working with multiple Bootstrap collapse elements?

One challenge I'm facing is with the Bootstrap collapse elements on my website. I have several of them, each controlled by a read-more button that includes an icon to indicate the state of the collapse element. However, when I add a class to the butto ...

Showing JSX/HTML content depending on the props received

Can you identify the name of this type of expression and do you know in what scenarios it should be applied? {props.type === "big" && <h2>{props.title}</h2>} ...

Using Object.defineProperty in a constructor has no effect

I recently revamped my three.js project and ran into a peculiar issue where all objects were being rendered with the same geometry and material. Upon further investigation in the debugger, I narrowed down the problem to this constructor: function Geometry ...

Unable to assign a value to a variable in JavaScript

Today, I delved into the world of JavaScript and decided to test my skills by creating a page that changes images when clicking on a div. Everything worked perfectly until I wanted to add an input element to specify how many steps to jump each time the but ...

What is the reason for having to add my IP to the white-list daily?

As a beginner, I am delving into the world of back-end development with Node.js, Express.js, and Mongoose for educational purposes. My database is hosted on Atlas-Mongo DB. Initially, everything seemed to be running smoothly as I configured it with the fre ...

Creating a JSX.Element as a prop within a TypeScript interface

I need to create an interface for a component that will accept a JSX.Element as a prop. I have been using ReactNode for this purpose, but I am facing issues when trying to display the icon. How can I resolve this issue? export interface firstLevelMenuItem ...

Why am I unable to utilize an array in this manner in JavaScript, and what is the method for accessing the array using a calculated number?

var nodesXY = ['15% 15%','30% 16%','19% 42%','39% 80%',]; var number = ["0","1","2","3","4","0","0","0"]; //some loop AccesNodes(number[1]); function AccesNodes(number){ console.log(number); // ...

Concealing a child component when hovering over its parent element with styled-components

I have a react component structured like this - const MyComponent = () => ( <ContainerSection> <DeleteButtonContainer> <Button theme="plain" autoWidth onClick={() = ...

Utilizing unique background images tailored to different screen resolutions

In order to enhance the user experience on my website, I am looking to implement a feature that dynamically changes the background images based on the user's screen resolution. My plan is to use a small snippet of JavaScript within the <head> s ...

Guide on adding HTML to a specific div element in jQuery by utilizing the keyword "(this)"

I have been working on a script for my PHP page in Wordpress to add titles to images in my photo gallery that open in a lightbox. Here's what I developed: $(".responsive1").bind("click", function() { $(this).("<div class='imgTitle ...

Material-UI icons refusing to show up on the display

I've been working on creating a sidebar component and importing various icons to enhance the UI, but for some reason they are not displaying on the screen. I even tried other suggested solutions without success. <SidebarOption Icon = {InsertComment ...

I need to figure out how to nest a div inside of a ul-li-a and ensure that the text inside the

In my search button, I have a cached list of options. When I select one, it should trigger the menu and choose the correct option. However, I am having trouble comparing the innerText of a div with the selected option from the search area. Both a and div e ...

Angular directive button failing to trigger ng-click event

Recently, I started working with Angular and ran into an issue while trying to set up a custom directive. The purpose of this directive is to display a button upon hovering over it, which, when clicked, should trigger a function within the directive. The b ...

Generate a fresh array using a current array comprising of objects

Greetings! I am facing a challenge with an array of objects like the one shown below: const data = [ {day: "Monday", to: "12.00", from: "15.00"}, {day: "Monday", to: "18.00", from: "22.00"}, {day: ...

Parsing of CSS and Javascript is disabled within iframes

Within my node.js application, I have configured an endpoint where I can load some parsed HTML code. This is achieved through the following code: app.get('/code', function (req, res) { res.setHeader('Content-Type', 'text/html& ...

Challenges with Angular 4 service initialization

Having trouble with my authentication service. The constructor is being called 259 times when making an HTTP request, but only once when the call is removed. I am using a shared module to provide a unique instance of the service. Angular version: 4.4.4 C ...

Ways to efficiently incorporate data into App.vue from the constructor

My app initialization uses main.js in the following way, import App from './App.vue'; const store = { items: [{ todo: 'Clean Apartment.', },{ todo: 'Mow the lawn!', },{ todo: 'Pick up ...

Interactive Notification System with MySQL, AJAX, and PHP

Seeking assistance for code conversion from async ajax to sync ajax. The current code is causing system lag after 20 minutes of inactivity. Likely issue resides within the code snippet provided below. function addmsg20(type, msg, data) { $('# ...

Integrate ng-admin with ui-router for enhanced functionality

My AngularJS project (version 1.4.9) is built using ui-router and contains multiple states defined as follows: .state('overview', { url: '/overview', parent: 'dashboard', templateUrl: 'views/dashboard/overview.html ...

Comparing strings in AngularJS

Struggling to compare two strings in AngularJS, I've come across various examples online. From what I understand, there are different methods like angular.equals(str1, str2), ===, and == if you're certain both are strings... Despite trying all t ...