How to effectively utilize $emit in Angular?

Whenever I use {{callData}} in my HTML, the result of $scope.callData doesn't seem to be functioning properly. Is there something wrong with my code? I would greatly appreciate any help in resolving this issue.

 phonecatControllers.controller('PhoneListCtrl', 
  ['$scope', 'Phone', function($scope, Phone){
    $scope.phones = Phone.query();

    $scope.sortir = 'age';
    $scope.getCount = function(){
      return $scope.phones.length;
    };
    $scope.$emit('showData', {
      showData: $scope.getCount
    });
    }]);

    phonecatControllers.controller('PhoneDetailCtrl', ['$scope', '$routeParams', 'Phone',
    function($scope, $routeParams, Phone) {
        $scope.phone = Phone.get({phoneId: $routeParams.phoneId}, function(phone) {
         $scope.mainImageUrl = phone.images[0];
      });

    $scope.setImage = function(imageUrl) {
      $scope.mainImageUrl = imageUrl;
    }
    }]);

    phonecatControllers.controller('JumlahCtrl', ['$scope',
    function($scope) {

      $scope.$on('showData', function(event, obj){

          console.log(obj);
          $scope.callData = function(event){
            obj.showData();
          };
    })
    }]);
<div>
  <span>jumlah : {{callData()}} </span>
</div>

Why is the result of $scope.callData not displaying correctly?

Answer №1

$scope is restricted to its own controller. To make it accessible at a broader level, you should use $rootScope instead. You can accomplish this by modifying

$scope.$emit('showData', {
   showData: $scope.getCount
});

as follows:

$rootScope.$broadcast('showData', {
   showData: $scope.getCount
});

Answer №2

If I could provide feedback on the question, I would mention that in the code snippet you shared, there are no ng-controller directives specified for the div element. As a result, the HTML doesn't recognize any Angular functions.

<div ng-controller="MyCtrl">
    <span>jumlah : {{callData()}} </span>
</div>
var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.callData = function() {
        return 123;
    }
}

For a visual demonstration, you can view this jsFiddle example: http://jsfiddle.net/5uu2cq6j/

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

What is the best way to enhance the class following this condition in JavaScript?

Initially, the original script worked perfectly with just one class being added: function check_btn_charge() { if (parseInt(jQuery(".total-change-price").text()) >= 0) { jQuery(".btn-action-save-charge"+"&nbsp;"+"btn-danger" ...

Double Looping of Ajax on Shopify Order Form

I have an Ajax order form on a product page. Every time the #submit-table button is clicked, it should display a drop-down menu with updated cart information, such as quantities and prices, along with the newly added products. Here's an example of th ...

Filter the ng-options by the value in a separate dropdown menu

I am having trouble with this code, even though it seems straightforward. My goal is to filter the 'model' dropdown based on the selected 'make'. Make: <select ng-model="makeng" ng-options="option.display for option in ...

Tips for managing the submission process for dynamically generated formsORStrategies for

<tr> <form role="form" class="manualImportSubmit" action="http://localhost:5000/XXX" method="post"> <td><input name="yyy" value="FormAValue" type="hidden">TestA</td> <td><input name="before_year" class="fo ...

Deploying a WebAPI to the api directory of an Angular app hosted on IIS results in 500 errors when making requests

I have been working on developing an angular application with a WebAPI 2 backend. The two components are in separate repositories, directories, and environments - the angular project is not part of a Visual Studio project and I am using WebStorm to work on ...

Utilizing ThreeJS to Implement Targeted Bloom Effects on Individual Object Components with Emission Mapping

I have a project where I need to showcase 3D objects with small LED lights that should emit a glow effect. I've attempted to use UnrealBloom, but the issue is that it affects the entire scene and makes everything look blurry, not just the parts with t ...

Assigning values to objects in Vue: setting data properties

I am working with a Vue.js app and attempting to update a value inside an object. Specifically, I want to change the 'name' value when the @change="onfilechangev" event occurs. Is there a way to achieve this, or is it not possible to update an ob ...

HTML not updating after a change in properties

My template is structured as a table where I update a column based on a button click that changes the props. Even though the props are updated, I do not see the template re-rendered. However, since I am also caching values for other rows in translatedMessa ...

What could be the reason behind ng-bind-html only displaying text and not the link?

Utilizing ng-repeat to exhibit a list on my webpage. One of the fields in my data contains a URL that I want to display as an actual link within my HTML page. Please refer to the screenshots below: My HTML: https://i.sstatic.net/2Gj1U.png My rendered pa ...

Modify ng-class within ng-repeat by utilizing ng-click

Is there a way to dynamically update the CSS class of an element within an ng-repeat loop in AngularJS? HTML <div ng-repeat="item in items"> <button ng-class="{'red': color == true, 'blue': color == false}" ng-click="change ...

eliminating attributes from a JavaScript object

Seeking a method to strip object properties before sending them to the front-end. Why does this code work as intended: var obj = { name: 'cris', age: 22, } console.log(obj) //displays name and age delete obj.name console.log(obj) //dis ...

Having trouble with the JavaScript DOM rewrite for aligning text?

function modifyTextAlignment(){ document.getElementById("th1").style.textAlign = "right"; } #th1{ text-align:left; } <table> <tr><center><th colspan="2" id="th1">List of Important Emergency Contacts</th><center></tr& ...

Fuzzy background when you scroll

My container has an image that blurs when you scroll down the page by 50 pixels. I feel like I've seen this effect somewhere before, but I can't quite recall where. I want the text to remain unaffected and not turn blue. Here is the HTML: <d ...

Save a PNG file using the HTML5 Canvas when the Submit button is clicked, with the help of PHP

I am looking for assistance with a signature capture form. I came across a standard template on Github that works perfectly, but I wanted to customize it further. However, my Javascript skills are still in the early stages. The current code allows you to c ...

Issue with draggable div containing gmap not functioning on mobile browsers

Is it possible to make a specific div draggable without dragging the content inside, such as a gmap widget? I have tried implementing this functionality in my code and it works on a computer browser but not on a mobile browser. Here is the simplified versi ...

Burst or displace meshes outward from the center

I am attempting to separate all the meshes that make up the loaded obj file from each other in order for the user to easily view each mesh individually. I am striving to replicate a similar functionality as shown in this example: Demo To achieve this ef ...

"Experiencing issues retrieving user-modified values in NativeScript's TimePicker component

I'm having trouble retrieving the user-modified value from a TimePicker. Instead of getting the modified value, I keep receiving the original value that was initially set in the control. Below is my component template: <TabView [(ngModel)]="tabSe ...

The dynamic JavaScript in Bootstrap 4 seems to be malfunctioning, despite working perfectly in Bootstrap 3

I am currently implementing a dynamic modal feature using the code snippet below: // Show Ajax modal with content $(document).on('click', '[data-modal]', function (event) { event.preventDefault(); $.get($(this).data('moda ...

The nested directive link function failed to execute and the controller was not recognized

Apologies in advance for adding to the sea of 'mah directive link function isn't called!' posts on Stack Overflow, but none of the solutions seem to work for me. I have a directive named sgMapHeader nested inside another directive called sg ...

Is there a way to input data into an AngularJS modal?

I'm looking for some assistance : How do I go about loading data into the content of an angular modal? Is there a way to load custom data for a selected item? ............................................................. This is the code ...