What is the best way to update the $scope of a directive from another directive's controller in Angular.js?

One of my directives is responsible for loading a list of events from a service:

.directive('appointments', [function () {
        return {
            restrict: 'CE',
            scope: {
                ngTemplate: '=',
            },
            controller: ['$scope','calendarService', function ($scope, calendarService) {
               var vm = this;
               vm.events = calendarService.getEvents();
            }],
            controllerAS:'vm',
            link: function (scope, elem, attrs) {
                scope.getTemplateUrl = function () {
                    if (angular.isDefined(scope.ngTemplate))
                        return scope.ngTemplate;
                    else
                    return "/list.directive.html";
                }
            },
            template: '<div ng-include="getTemplateUrl()"></div>'
        }
    }])

Now I have another directive where I want to update this list. How can I do that in the first directive's controller?

.directive('appointmentsUpdate', [function () {
            return {
                restrict: 'CE',
                scope: {
                    ngEventId: '=',
                },
                controller: ['$scope','calendarService', function ($scope, calendarService) {
                   var vm = this;
                   vm.update = calendarService.updateEvent(scope.ngEventId).then(function(res){


   // The newly created item should be added to the List (vm.events) from the first directive

)
});
                }],
                controllerAS:'vm',
                link: function (scope, elem, attrs) {
                    scope.getTemplateUrl = function () {
                        if (angular.isDefined(scope.ngTemplate))
                            return scope.ngTemplate;
                        else
                        return "/list.directive.html";
                    }
                },
                template: '<div ng-include="getTemplateUrl()"></div>'
            }
        }])

Answer №1

Utilize the angular broadcast service to achieve this functionality:

In the first directive, implement the following code snippet:

 $rootScope.$broadcast('greeting', data_to_be_sent);

In another directive, listen for the event and update its scope accordingly:

$scope.$on('greeting', processGreeting)

  function processGreeting($event, message){
    alert(['Received Message',message].join(' : '));
  }

Answer №2

In order for directives to communicate with each other, the require property is used.

It works something like this:

return {
    restrict: 'AE',
    require: '^ParentDirective or ^SameLevelDirective'
}

If you need a more in-depth explanation, check out this resource on Directives That Communicate by ToddMotto.

Answer №3

Singleton services ensure that when you make changes to a list in one location using calendarService.updateEvent(), the updated list will be reflected when you retrieve the data from the service in another directive. You can implement a watch function to monitor updates to the list:

$scope.$watch(() => calendarService.getEvents(), (newValue, oldValue) => {
    // Update your scope with the latest list
}, true);

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

Using AngularJS to handle Access-Control-Origin Header when making HTTP requests

Currently, my backend is set up using nodejs and angularjs is being used for the frontend. Within my frontend application, I am trying to access a feed located at ''. Unfortunately, I am encountering an error related to access-control-origin. ...

Utilizing Angular to apply multiple ng-repeat directives with multiple filters

I am working on a project that involves multiple ng-repeat lists with several filters. Currently, I am using (ex:A.value) if (ex:B.value), but I would like to implement multiple filters. The filters I want to incorporate are recommend_search, skill_searc ...

There seems to be an issue with your SQL syntax that is preventing the data from being entered correctly into the database using Node.js, MySQL, and Express

After successfully displaying data from my database, I attempted to add data to it using the following code snippet: exports.tambahData = (req, res) => { var keyy = req.body.keyy; var valuee = req.body.valuee; var brand = req.body.brand; ...

What are the steps to create a connect4 board featuring rounded corners and curved sides?

How can I create a Connect4 board with the exact styles and properties shown in the image? I want to achieve the curved sides effect as displayed. Can this be done using only HTML elements, or is there an easy SVG solution available? Here is my current co ...

What is the best way to retrieve a value from a form and incorporate it into a controller?

Here is the code I've been working on: http://pastebin.com/AyFjjLbW I started learning AngularJS and was making progress, but now I'm facing a challenge. I'm trying to use a drop-down menu to select both a priority level and a type of job t ...

javascript The event handler is not functioning properly for the dynamically loaded AJAX content

I am facing an issue with adding a JavaScript event listener to a dynamically loaded div via AJAX. Below is my code snippet: var QuantityMiniCart = function() { var infor = document.querySelectorAll( '.mini-cart-product-infor' ); if ( ...

Utilize the dynamic duo of GridLayout and ScrollView within the Famo.us JS framework

I'm attempting to incorporate a grid layout into a scroll view using famo.us (with angular), and the most straightforward approach seems to be working. <fa-view> <fa-scroll-view fa-pipe-from="eventHandler" fa-options="scrollView"> ...

How to set textboxes as read-only depending on the drop-down choice?

After developing some scripts to automatically populate the data-length and data-width in textboxes based on a dropdown selection, I now face the challenge of making the .width and .length textboxes readonly depending on the selected dropdown option. Is t ...

Creating a personalized cover for devextreme column in datagrid: A Step-by-Step Guide

I have encountered an issue with wrapping a Column inside my DataGrid. My goal is to create a customized component that generates a Column with the correct formatting. For instance, I want to develop a ColumnDate component that includes specific date forma ...

Manipulating DropDownList Attributes in ASP.NET using JavaScript

I am facing an issue with populating a Dropdownlist control on my ASCX page. <asp:DropDownList ID="demoddl" runat="server" onchange="apply(this.options[this.selectedIndex].value,event)" onclick="borderColorChange(this.id, 'Click')" onblur="bo ...

Is it possible to turn off Angular CLI ng build linting for a specific directory?

I am facing an issue with a specific directory in my project template that I want to exclude from linting. Despite excluding it in both tsconfig and eslint, running eslint works fine but when using ng build, the directory is still included in linting and e ...

Retrieving all users in Sqlite database with a specific value

I am looking to identify and access each user who has a specific value in their row. Here is an example code snippet of what I want: sql.prepare("SELECT * FROM raid WHERE raid1 > 0 AND NOT id='685337576810610734'").get().forEach(async (user) ...

The attempt to execute 'removeChild' on 'Node' was unsuccessful because parameter 1 is not the correct type. Although it did remove the elements from the DOM, it only did so once

It's quite a challenge I'm facing!!! Although there have been similar questions asked before, they were all for specific scenarios. I am currently developing a tictactoe game using the module design pattern. The function below helps me create tw ...

Having trouble accessing properties within a JavaScript object array in React.js?

I have a React.js component that fetches its initial state data from an API call in the componentDidMount(). This data comprises an array of objects. While I can see the entire array and individual elements using JSON.stringify (for debugging purposes), a ...

Displaying HTML content using Typescript

As a newcomer to typescript, I have a question regarding displaying HTML using typescript. Below is the HTML code snippet: <div itemprop="copy-paste-block"> <ul> <li><span style="font-size:11pt;"><span style="font-family ...

Exploring Data and Models within AngularJS

I am working on a WebApp that has a unique HTML layout Nav-column-| Center Column---- | Right Column Link1---------|Data corresponding|Data Corresponding to Link1-A Link2---------| to Nav-column------| (ie based oon Center Column Link) Link3----- ...

ASP.NET ensures that the entire page is validated by the form

Is it possible to validate only a specific part of the form instead of the entire page? Currently, when I try to validate textboxes on the page, the validation is applied to all textboxes. Here are more details: https://i.stack.imgur.com/eowMh.png The c ...

jade, express, as well as findings from mysql

My goal is to display the results of an SQL query in Jade, which pulls data from a table of banners. Each banner has a unique id and falls under one of three types. Here is my current code : express : connection.query("SELECT * FROM banner_idx ORDER BY ...

Implementing Browser Back or Back button in AngularJS

Currently, I am developing an application that utilizes route methods to navigate between webpages for different modules. Essentially, it is a single page application with route methods responsible for loading the HTML content in the body section. The iss ...

Determine whether the response originates from Express or Fastify

Is there a method to identify whether the "res" object in NodeJS, built with Javascript, corresponds to an Express or Fastify response? ...