AngularJS: Share event from the parent component exclusively with its child components

I am looking to establish a way to broadcast an event from a parent directive to a specific child, without all children in every instance of the "parent" directive receiving it when using scope.broadcast in the parent directive link function.

Current Behavior: Currently, when the parent (1) broadcasts an event, both child (1.1) and child (2.1) receive the event.

Desired Behavior: I want to modify the functionality so that the event broadcasted from parent (1) is only received by child (1.1), excluding child (2.1).

In my directive, I have implemented code to check if an element is on the screen. I intend for only one directive to perform this function and be responsible for sending events to others.

<div>
    <div parent> <!-- 1 -->
        <div child></div> <!-- 1.1 -->
    </div>

    <div parent> <!-- 2-->
        <div child></div> <!-- 2.1 -->
    </div>
</div>

Answer №1

One possible explanation is that the parent directive and child directives share the same scope, causing events to propagate to all child directives.

The solution is for each directive to have its own scope that prototypically inherits from the parent. ($root <-- parent <-- child)

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="85e4ebe2f0e9e4f7abeff6c5b4abb1abb2">[email protected]</a>" data-semver="1.4.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script>
      angular
        .module('app', [])
        .directive('parent', function() {
          return {
            scope: true,
            link: function(scope, element) {
              element.on('click', function() {
                scope.$broadcast('parent-event');
              });
            }
          };
        })
        .directive('child', function() {
          return {
            scope: true,
            link: function(scope) {
              scope.$on('parent-event', function() {
                console.log('child(' + scope.$id + ') caught parent event');
              });
            }
          };
        });
    </script>
  </head>

  <body>
    <div>
      <div parent> Parent {{ $id }}
          <div child>Child {{ $id }}</div>
      </div>

      <hr />

      <div parent> Parent {{ $id }}
          <div child>Child {{ $id }}</div>
      </div>
  </div>
  </body>
</html>

Plunker

Answer №2

When broadcasting data, it is sent to all child scopes by default. One potential solution could be:

$scope.$broadcast('customEvent', {
    target: ['dir1', 'dir2'],
    someProp: 'Sending an Object!' // include any desired data
});

Then, in directive one:

$scope.$on('customEvent', function (event, data) {
   if(data.target.indexOf('dir1') === -1 ) return;
});

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

Ways to conceal a badge using JavaScript

Can anyone help me figure out how to edit the data-count of a badge and hide the badge using JavaScript in a Bootstrap 5 navbar with a stacked Font Awesome icon? I have tried the following: document.getElementsByClassName("p1 fa-stack fa-2x has-badge ...

Leverage the power of JSON to efficiently represent a collection of string

Currently, I am engrossed in reading the 3rd edition of JavaScript Pocket Reference. The author makes an interesting statement in chapter 5 - Objects on page 75: In JavaScript, objects are dynamic, allowing properties to be added and deleted at will. Int ...

How can I implement jQuery autocomplete with customized settings?

In my Drupal project, I am looking to implement jQuery's auto complete feature to search for nodes based on their titles. I am having trouble finding examples that align with my specific requirements: The URL structure should be: /api/node/title/{wh ...

Capture a screenshot of the icons

I'm curious about displaying specific parts of images in a React Native application. class InstaClone extends Component { render() { return( <View style={{ flex:1, width:100 + "%", height:100 + "%" }}> <View style={st ...

Unlocking the power of keys in manipulating JSONP objects

i am uncertain about the accuracy of my title, as i am unsure how to label the task at hand... "modifiers":{"agility":{"type":"attribute","displayname":"agi","value":46}} forms a part of a jsonp callback that is received from this source. i am attempting ...

Is it possible for the NextJS Client component to only receive props after rendering props.children?

Encountering a puzzling issue that has me stumped... In my setup, I have a server side component that fetches data and then sends it over to the client component, which is all pretty standard. Here's where things get weird... When I log the data on ...

What are the steps to ensure that data retrieved from an API is accurately displayed in a table?

My current goal is to collect data from the crypto compare API and display it in a table format. Although I am able to generate the necessary elements and append them to the table body, I am facing an unusual issue. Each time I use a for loop to iterate th ...

Tips for sending web form data straight to Google Sheets without the need for an authentication page

Exploring the Concept I have a unique idea to develop a landing page with a form that captures visitors' email addresses in a Google Sheet. After discovering a helpful post containing a Google App script for this purpose, I followed the guidelines o ...

Integrating Dart with external libraries

Here is a straightforward example demonstrating the usage of a map library: <!doctype html> <html> <head> <script src="http://api4.mapy.cz/loader.js"></script> <script>Loader.load()</script> </head; &l ...

I am experiencing some issues with React Router V4's functionality

I am currently developing a web application where I intend to showcase user details on the same page using routers when they are clicked. Below is my index.js file: window.React = React; render(<div> <Menu/><MainMenu/><App/>&l ...

What is the best way to implement a conditional check before a directive is executed in Angular, aside from using ng-if

I am facing an issue where the directive is being executed before the ng-if directive. Is there a way to ensure that the ng-if directive is executed before the custom directive? Could I be making a mistake somewhere? Should I consider using a different ...

What's the quickest method for duplicating an array?

What is the quickest method for duplicating an array? I wanted to create a game, but I found that Array.filter was performing too slowly, so I developed a new function: Array.prototype.removeIf = function(condition: Function): any[] { var copy: any[] ...

What is the reason for not allowing return statements in the ternary operator?

Imagine you have a basic form and you want to determine if the form has been modified. If it has changed, you want to submit it; otherwise, you want to prevent form submission. To tackle this, instead of using an if-else statement, I decided to go for a te ...

Is it possible to circumvent the use of ng-repeat in any manner?

When displaying JSON data in an Ionic view using multiple ng-repeats, the console log shows that the data is retrieved quickly. However, it seems that having multiple ng-repeats is causing a slowdown in performance, resulting in the app freezing and taking ...

Exploring the world of AngularJS for the first time

I'm currently delving into the world of AngularJS and I encountered an issue with my first example. Why is it not working as expected? Here's a look at the HTML snippet: <html ng-app> <head> <title></title> <sc ...

Something seems off with the performance of Gulp-filter and it is not

I am struggling with the following piece of code: gulp.src('src/*.*') .pipe(filter(['**', '!**/*.{png,jpg,bmp,jpeg,jpeg2,webp,svg}', '!**/*.{css,less}'])) .pipe(gulp.dest('dev/')); This code is sup ...

Controller unable to access form inside ng-repeat loop in AngularJS

Looking to access a form object within my controller. The form is located inside an ng-repeat block with a dynamic name, and I should be able to access it since version 1.3. JavaScript: var app = angular.module('app', []); app.controller(' ...

typescript: define the type of an object that behaves like a map

My current approach involves utilizing an object to store a map, where keys are strings and values are of a fixed type T. Upon looking up a key in the object, the type inference automatically assigns it the type T. However, there is a possibility that it ...

Screening data entries

.js "rpsCommonWord": [ { "addressWeightPct": "60", "charSubstituteWeightPct": "15", "nameWeightPct": "40", "oIdNumber": "21", "shortWordMinLthWeightPct": "100", "substituteWeightPct": "5", ...

Sending data from a file reader to a service in Angular JS

I am currently utilizing a file reader to retrieve data from a file upload. Although I can successfully fetch the data in controller.js, I am facing difficulties when attempting to pass it to the API service as the data always appears empty. Here is the up ...