Passing events from one controller to another in AngularJS using methods such as $broadcast and $window.localStorage

Looking to dispatch an event to another controller, I am familiar with techniques involving $rootScope.$broadcast, $scope.$emit, and then listening for the event using $scope.$on.

This is a common approach, but in my project, controllers are initialized in separate JavaScript files.

//In broadcaster.js
function broadcasterCtrl(~~~~~, broadcasterService){
~~~~~~~~~~
}
function broadcasterService(~~~~~){
~~~~~~~~~~
}
angular
    .module('myApp')
    .service('broadcasterService', broadcasterService)
    .controller('broadcasterCtrl', broadcasterCtrl);

//In listener.js
function listenerCtrl(~~~~~, listenerService){
~~~~~~~~~~
}
function listenerService(~~~~~){
~~~~~~~~~~
}
angular
    .module('myApp')
    .service('listenerService', listenerService)
    .controller('listenerCtrl', listenerCtrl);

Due to this setup, the listener controller is initialized when the view(state) is called. As a workaround, I used

$window.localStorage.setItem('key', value)
, although I have concerns about its security vulnerabilities.

Are there alternative approaches utilizing $broadcast? Or is it safe to rely on localStorage?

Answer №1

The most effective method for disseminating information among multiple controllers is through the use of services. Services act as singletons, making it simpler to organize and segregate a scope/variables for that specific purpose.

var app = angular.module('myApp', []);
    app.factory('datepickerinfo', function() {
        var keyValue;

        datepickerinfo.setKey = function(key) {
            keyValue = key;
        };
        datepickerinfo.getKey = function(){
        return keyValue;
    }

    return datepickerinfo;
});

Then, inject it:

function MyCtrl($scope, datepickerinfo) {
    $scope.dateKey = datepickerinfo.getKey();
}

LocalStorage:

Another option is utilizing local storage. However, it is important to note that sensitive data should not be stored in local storage. For non-sensitive information, local storage can offer a useful solution. It's crucial to handle local storage properly whenever updates or deletions are made.

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

Preventing Multiple Modals from Opening in Angular UI Bootstrap

I have successfully set the backdrop option to false for the modal directive using $modal.open. However, I am facing an issue where multiple modals can be triggered to open. Is there a way to prevent the trigger button from opening another modal once one i ...

Is there a way to achieve a similar outcome on my site?

Recently, I noticed a mouse-hover effect on two websites and found it quite appealing. https://i.sstatic.net/Ly0gP.png https://i.sstatic.net/oDe1i.png This is the specific effect that caught my attention. Can anyone provide me with insight on how to impl ...

Navigating asynchronous URL parsing in NodeJS

I am still fairly new to the world of Node.js and Javascript, so I appreciate your patience with my confusion around the callback mechanism Bacchanalia. The Issue at Hand I'm currently working on a basic Node.js application that is responsible for h ...

What is the process of declaring internal class variables within class methods in JavaScript?

Here's a query related to React JS. Can I define internal class variables within a method and then use them in other methods? For instance: class Something extends React.Component { state = { value: 'doesnt matter' }; somethin ...

How to extract a subset of data from an existing object and create a new object in Vue JS

My latest project involves creating a search app to find products. I have implemented a PHP script that returns results in JSON format when a keyword is submitted. The data retrieval is done using axios. The challenge I am facing is with handling the disp ...

Direcscope directives can be replaced

When using this directive and implementing a `ng-repeat`, I have noticed that the `console.log` always returns the last data from the iteration. (function () { 'use strict'; angular .module('app.schoolAdmin') . ...

What does Event.target.id return - the HTML id value or the HTML name value?

HTML Form Example: <form id="form-product-add" style="display: inline;"> <input name="csrf" type="hidden" value="<?= $this->csrf; ?>"> <input type="hidden" name="a ...

What is the best way to implement toggleable divs using JavaScript's innerHTML method?

I am attempting to fetch data from an XML file and generate a name that, upon being clicked, will reveal more information. The additional details will be contained within a div element that remains hidden until the header is clicked. This is the concept. ...

The ng-controller directive is functional, however the controller in $state is not working as expected

Encountering an issue with the $elementProvider not being detected when attempting to define a controller on the $state. For instance: .state('tournament', { url: '/tournament', controller: 'TournamentController', te ...

Excessive delay in executing Javascript loops

While developing an EMI calculator for a hybrid mobile app, I encountered a performance issue. The execution within one of the loops takes too long, resulting in the page becoming unresponsive. Here is my code snippet: var EMICalculator = { basicEMI: fun ...

Incorporate AngularJS {{expression}} into ng-repeat by utilizing a separate array

After completely rebuilding my website (which was originally hacked together with Wordpress), I decided to utilize Laravel and AngularJS. The transition has been quite challenging, but I'm almost there, except for one issue. On my website, I have &ap ...

Encountering a problem while trying to run npm publish with public access, error code E

I've encountered an issue when attempting to publish a scoped package on npm, where I consistently receive this error via the CLI: npm ERR! code E403 npm ERR! 403 403 Forbidden - PUT https://registry.npmjs.org/@username%2fdynamic-ui-elements - Forbidd ...

Chrome reports a Javascript error: indicating that it is not recognizing the function

When working with a js file and html, I encountered an issue where one function works fine but another prompts an error in Chrome: Uncaught TypeError: specification_existing is not a function I'm puzzled as to why one function works while the othe ...

Navigating through segments of an array in javascript

Within my condensed array, I have omitted most of the input data to demonstrate a particular task. For illustrative purposes, here is an extensive example showcasing the elements: storyArray=["#C1", "String showing first message", "String displaying secon ...

Having trouble with Vue i18n and TypeScript: "The '$t' property is not recognized on the 'VueConstructor' type." Any suggestions on how to resolve this issue?

Within my project, some common functions are stored in separate .ts files. Is there a way to incorporate i18n in these cases? // for i18n import Vue from 'vue' declare module 'vue/types/vue' { interface VueConstructor { $t: an ...

Tips for storing arrays in AngularJS with JavaScript

I am new to using JavaScript. I have a function that stores objects in an array to an Angular model. Here is an example: function getSpec(){ debugger var i; for(i=0;i<main.specifications.length;i++){ main.newProduct.Specification= ( ...

Using node.js to display a directory's contents

I am new to node.js and I am facing an issue. I am trying to display the filename and last modification date in a list using EJS view. However, the problem I am encountering is passing the variables to my view. I am trying to populate an arraylist with fi ...

An intuitive approach to adding a CheckBox control within a GridView using JavaScript and SPAN elements

Struggling to calculate the total quantity from the gridview for checked row checkboxes? Having trouble accessing the checkbox control in your JavaScript? Below is the code snippet you provided, but it's not returning anything. <table cellspaci ...

Alter the style type of a Next.js element dynamically

I am currently working on dynamically changing the color of an element based on the result of a function //Sample function if ("123".includes("5")) { color = "boldOrange" } else { let color = "boldGreen" } Within my CSS, I have two clas ...

Fixing errors with observables in an Angular 2 project using Rx

var foo = Observable.create(function(observer){ try{ console.log('hey there'); observer.next(22); throw new Error('not good at all'); setTimeout(function(){ observe ...