pass information between sibling directives

I am currently experiencing an issue with an AngularJS directive. I am trying to send an outlet object from directive1 to directive2, both of which share the same controller scope. I have attempted to emit an event from directive1 to the controller, broadcast that event from the controller to directive2, and listen for the event on directive2, but it has not been successful.

Directive1:

angular.module('moduleName')
.directive('directive1', function() {
    return {
        restrict: 'E',
        templateUrl: 'directive1.html',
        scope: false,
        link: function(scope) {
            scope.selectOutlet = function(outlet) {
                scope.order.entityId = outlet.id;
                scope.navigation.currentTab = 'right';
            };
        }
    };

In directive1, the function scope.selectOutlet() sets the outletId to scope.order.entityId. I would like to move or set that line of code to the save function in directive2.

Directive2:

angular.module('moduleName')
.directive('directive2', function(config, $rootScope, $state) {
    return {
        restrict: 'E',
        templateUrl: 'directive2.html',
        scope: false,
        link: function(scope) {
            scope.save = function() {
                // Save functionality  
                // scope.order.entityId = outlet.id; This is what I would like to do
            };
        }
    };
});

Any assistance would be greatly appreciated.

Answer №1

One approach is to utilize a factory or a service, and then inject that factory into your directive. By doing this, you can easily set the data within the function defined in the factory. Here is an example using a factory:

app.factory('shared', function() {
   var obj = {};
   
   obj.setData = function() {
      // Call this function from directive 1.
   }
   
   return obj;
});

By including this factory in your directives, you can access the data in multiple directives. If this explanation is not clear, I can provide a demo on jsfiddle or plunker for better understanding.

Answer №2

Execute the following steps within the initial directive

angular.module('moduleName')
  .directive('directive1', function($rootScope) {
   return {
    restrict: 'E',
    templateUrl: 'directive1.html',
    scope: false,
    link: function(scope) {
        scope.selectOutlet = function(outlet) {
             $rootScope.$broadcast('save:outlet',outlet);
            //scope.order.entityId = outlet.id;
            //scope.navigation.currentTab = 'right';
        };
    }
};

Additionally, perform the following in the second directive

angular.module('moduleName')
 .directive('directive2', function(config, $rootScope, $state) {
   return {
    restrict: 'E',
    templateUrl: 'directive2.html',
    scope: false,
    link: function(scope) {
       $rootScope.$on('save:outlet',function(event,data){
         // implement actions here 
       });
    }
   };
 });

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

Printing array of API results in NodeJS using ExpressJS

I have been working with the Twitter API to retrieve tweets and store them in an array. I am looking to print the entire array on my HTML document for display purposes. Excited to see it work! Thanks! Check out the code snippet below: var express = requi ...

Seamless integration of Applitools with WebdriverIO

Seeking assistance to integrate Applitools with my WebdriverIO project. Find the specifications below: Node Version: v12.18.2 NPM Version: 6.14.5 WebdriverIO Version: 6.3.6 The service in my wdio file is configured as follows: services: ['selenium-s ...

Steps to partially open the Modal Sheet Swipe Step by default

I've set up a modal sheet component with the following structure: <f7-sheet class="myClass" style="height: auto" swipe-to-step :backdrop="false" > <div class="sheet- ...

Tips for transferring HTML code to a controller

Currently facing an issue while working with MVC and attempting to store HTML code from a view in a database field. In the JS section of my MVC solution, I have the following code snippet: var data = { id_perizia: $("#id_perizia").val(), pinSessione: $("# ...

What is the best way to transform an array of objects into a single string in JavaScript?

After receiving the input from req.body, it looks like this: [ { "Name": "Test_1", "Level 1": "Story_1", "Level 2": "Story_1.1" }, { "Name": & ...

Adapt vanilla JavaScript code to be compatible with Node.js, MongoDB, and Express framework

In the midst of working on a blog project for my class, I find myself faced with the challenge of integrating Nodejs, Mongo, and Express into our existing setup. Up until now, we have been gradually transitioning to using Express in our application develop ...

When an AJAX request is successful in Angular, utilize the ng-hide directive

I've implemented a feature where double-clicking the name displays an input field, but I'm facing an issue with switching back after a successful put-request. Despite setting $scope.edit to false, it doesn't seem to work as expected. This is ...

Troubleshooting a problem with $addToSet and $each in Mongo and Node.js

I'm facing an issue while using $addToSet to add an array of Strings to a MongoDB database. The Object setup is defined as follows: var mongoose = require('mongoose'); var Schema = mongoose.Schema; module.exports = mongoose.model('Co ...

There appears to be an issue with the function's ability to

I'm currently facing an issue with my script. There's an editable field and a button next to it, and I've created a function that should start working when the button is pressed, reading data from the input field. However, the function doesn ...

Dynamic anime-js hover animation flickering at high speeds

I have implemented the anime-js animation library to create an effect where a div grows when hovered over and shrinks when moving the mouse away. You can find the documentation for this library here: The animation works perfectly if you move slowly, allow ...

The toArray function in MongoDB does not support the use of Array push

I'm attempting to loop through all documents within collections, store them in a global variable, but it seems like the push() function is not working and returning an empty array [] inside of toArray(). Any ideas? const mongo = require('mongodb ...

The technique of using Javascript x to escape characters is

I've come across a handful of other software programs that feature a similar construct: let str = '\x32\x20\x60\x78\x6e\x7a\x9c\x89'; As I experimented with the sequence of numbers and letters within ...

Error TS2322: The function expecting a type of 'FormEventHandler<HTMLFormElement>' cannot be assigned the type '(data: TicketFullDTO) => Promise<void>'

I am currently working on creating an edit form to modify data from a database based on its ID. Here is my approach: import React, {FormEvent, useEffect, useState} from "react"; import TextField from "@material-ui/core/TextField" ...

What steps are needed to configure ESLint to exclusively analyze .ts files?

I need ESLint to exclusively focus on processing .ts files and not .js files. In order to achieve that, I made a .eslintignore file and included the following lines: *.js **/*.js Nevertheless, it appears that ESLint is disregarding this file. Is there so ...

After a period of activity, requests to Node.js with Express may become unresponsive

My server is running smoothly but after some time, it stops responding to requests. When I try to load the page, it gives me a "couldn't establish connection" error message. Here is my app.js: var express = require('express'); var path = r ...

Enabling the source map option for the TerserWebpackPlugin webpack plugin has a noticeable impact on the overall build time of webpack

I've made the decision to enable source maps for production. Utilizing TerserWebpackPlugin for minifying my js files, as suggested by webpack documentation. This plugin includes a config option for sourceMap, which according to the docs, should be ena ...

Looking to minimize the amount of HTML code in Angularjs by utilizing ng-repeat

Working with some HTML <tr class="matrix_row" ng-repeat="process in matrixCtrl.processes | filter : { park: parentIndex } track by $index"> <td class="properties" ng-click="dashboardCtrl.currParam=0; dashboardCtrl.currentProcess=process"> ...

Utilizing Firebase Cloud Firestore: A guide to programmatically handling indexes

Transitioning from Firebase Realtime Database to Cloud Firestore has presented some challenges in implementing "complex" queries across collections. Despite this, I am determined to make it work. My current setup involves using Express JS and Firebase Adm ...

Angular does not seem to support drop and drag events in fullCalendar

I am looking to enhance my fullCalendar by adding a drag and drop feature for the events. This feature will allow users to easily move events within the calendar to different days and times. Below is the HTML code I currently have: <p-fullCalendar deep ...

Exploring the use of AngularJS to retrieve information from a web service

I'm attempting to retrieve information from a web service and connect it to a scope variable in angularjs. The controller API is structured like this: public class ContactsController : ApiController { // GET: api/Contacts public List<Con ...