"Learn the art of refreshing data in AngularJS following the use of $emit event handling

I am in need of assistance with AngularJS. How can I re-initialize a variable in scope after using emit? Here is an example code snippet:

$scope.uiConfig = {title: "example"};

$scope.$emit('myCustomCalendar', 'Data to send');

$scope.$on('myCustomCalendar', function () {
  $scope.uiConfig = {title: "new Title"};
});

Answer №1

When you use the $on function, make sure to provide a callback that can receive parameters including your data:

$scope.$on('myCostumCalendar', function (event, data) {
  // The variable 'data' will hold the information you sent
  $scope.uiConfig = {title: "New Updated Title"};
});

Answer №2

var myApp = angular.module('myApp',[]);

  myApp.controller('mainEventController', ['$scope', function($scope) {
    $scope.count = 0;
  }]);
  myApp.controller('EventController', ['$scope', function($scope) {
    debugger;  

    $scope.$on('MyEvent', function() {
       debugger;

      $scope.count++;
    });
  }]);
<!DOCTYPE HTML>
<html>
<head>
<title>Basic on controllers</title>
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<script src="basiccontroller.js"></script>
</head>
<body ng-app="myApp">

<!-- emit and broadcast -->
<p><b>emit and broadcast</b></p>
<p>----------------------------</p>
 <div ng-controller="mainEventController">
Root scope <tt>MyEvent</tt> count: {{count}}
<ul>
<li ng-controller="EventController">
<button ng-click="$emit('MyEvent')">$emit('MyEvent')</button>
<button ng-click="$broadcast('MyEvent')">$broadcast('MyEvent')</button>
<br>
Middle scope <tt>MyEvent</tt> count: {{count}}
<ul>
<li  ng-controller="EventController">
Leaf scope <tt>MyEvent</tt> count: {{count}}
</li>
</ul>
</li>
</ul> 
</div>

</body>
</html>

Answer №3

The code snippet below is not producing the desired output:

When using inherited scope values in the $emit function, the result may be incorrect. Additionally, the emit function may not behave as expected the first time in AngularJS.

Please provide clarification on this matter.

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

Mapping drop-downs based on the length of a JSON array

Looking to generate dropdowns in a React Native mobile application based on the length of values in an API JSON array. Here's an example of the desired output: eg:- Choice 1 (Label of the Drop Down) -Sub Choice 1 . (Value Data) ...

Combine the elements within the HEAD tag into a group

I am currently developing a dynamic page system using AJAX. Whenever a link is clicked, an AJAX call is made to retrieve data from the requested page. However, I have encountered an issue where certain data in the page file needs to be placed within the h ...

Troubleshooting the malfunctioning of the Bootstrap slide animation

I've been attempting to implement scroll animation on a div, but for some reason, it's not working as intended. I must have made a mistake somewhere, but I can't figure out where. Any help in resolving this issue would be greatly appreciated ...

Having trouble compiling the Phonegap app on my computer

I am experiencing trouble compiling my app for iOS locally, while Android works without any issues. To set up, I have installed both cordova and phonegap using the command npm install -g [...]. I am operating on OSX (10.7.5). Here are the versions for bo ...

Why does Math.max.apply not prioritize the first parameter?

function findSmallestNumber(numbers){ return Math.min.apply(Math, numbers); } This code sets the context to be the Math object. However, this is not required because the min() and max() methods will still function properly regardless of the specified co ...

Tips for adjusting the minimum attribute within an input field with jQuery

In my form, I have an input field with arrows (up and down). Next to it, there are two buttons: + and -. When I click on the input field and then use the arrow, the system retrieves the value from a dropdown list, which works fine. However, when I use the ...

Using Vue.js, send information from an Ajax request to a Laravel controller for processing

As someone new to development, I have a little confusion with handling data from a multi-step form in an AJAX request on my controller. While I've been able to successfully collect all form inputs at once, I'm struggling to use the data from $req ...

Utilizing the onclick event to call a function with multiple arguments within Template literals

How can I properly write a function with multiple arguments using JavaScript post ES6 template literals when called by an onclick event? Here is my code: function displayImg(imageUrl, gameName, gameSummary, gameYear, cardId) { cardId = cardId.toStrin ...

"Clicking on a handler will replace the existing value when the same handler is used for multiple elements in

import React, { useState, useEffect } from "react"; const Swatches = (props) => { const options = props.options; const label = Object.keys(options); const values = Object.values(options); const colors = props.colors; const sizes = p ...

Display a JSON encoded array using Jquery

Within an ajax call, I have a single json encoded array set: $var = json_encode($_SESSION['pictures']); The json encoded array is stored in a variable called "array" When I try to display the contents of "array" using alert, I get this respons ...

I am encountering an issue with retrieving API JSON data in NextJS where I am receiving an

Instead of receiving data in my console log, I am seeing undefined. This is my Index.js file (located in the pages folder) import Head from "next/head"; import Link from "next/link"; import axios from "axios"; import Test fro ...

When it comes to assigning a background to a div using jQuery and JSON

I have been experimenting with creating a database using only JSON and surprisingly, it worked once I added a "js/" in the URL. However, my current issue lies with CSS. Let me elaborate. Here is the JSON data: [ { "title":"Facebook", ...

Problem with reordering rows in a PHP DataTable

While attempting to retrieve data from a database table and display it in a DataTable, I encountered the following error: DataTables warning: table id=example - Invalid JSON response. To learn more about this error, refer to http://datatables.net/tn/1 ...

Looking to adjust the fill pattern dynamically

I previously implemented this code: Is there a way to modify the fill image on my 3 buttons to display in 3 distinct colors instead? ...

What causes the axios Library to fail in initiating a request if the API call does not begin with "https://"?

This issue has been resolved, but I still want to ask it in order to gain a better understanding of the underlying processes. So, I am using an API to retrieve data on the current weather in a specific city. The API call (as per the provider's documen ...

Creating a custom design for legends in Chart.js

I'm currently working on a project using chart.js and I'm trying to customize the label/legend styling for my chart. My goal is to replace the rectangular legend with a circular one. I've come across the suggestion of creating a custom legen ...

"Looking for a solution to the ESLint error related to 'no-unused-var' and Google Maps integration. How can I effectively resolve

I'm struggling with what seems to be a simple problem I tried adding /* export myMap */ or /* global myMap */ at the beginning of the script but I keep getting errors Code HTML <h1>My First Google Map</h1> <div id="googleMap" ...

Global Day "Sequence" Initiates Subtraction Instead of Preserving Its Authentic Structure

While using Python's Selenium, I am facing a challenge when trying to "inject" an international date string in the specified format into a web page. Unfortunately, instead of getting the expected string, I am getting a result that seems like subtracti ...

ReactJS - Opt for useRef over useState for props substitution

Presented below is my ImageFallback component, which serves as a backup by displaying an svg image if the original one is not available. export interface ImageProps { srcImage: string; classNames?: string; fallbackImage?: FallbackImages; } const Im ...

Exploring AngularJS: How Child Directives Can Access Properties of Parent Directives

I am struggling with finding the best way to achieve a seemingly simple task. Here is my parent directive: directive('editableFieldset', function () { return { restrict: 'E', scope: { model: '=' }, re ...