Unable to access a function from a different controller within an AngularJS Ionic framework application

How can I trigger or call the callkhs function in the LihatKhsController from the KhsController?

function KhsController($scope, $rootScope){
     $scope.$emit('callkhs', {param:'test'});
}

I am attempting to retrieve parameter values from the KhsController to the LihatController:

function LihatKhsController($scope, $rootScope){
    $scope.$on("callkhs", function(event, data){
      console.log('Hello callkhs', data.param); //not displaying
    });
}

Any assistance in resolving this issue would be greatly appreciated.

Answer №1

When using $scope.$emit, it will only notify its parent scope.

For example:

<div ng-controller="LihatKhsController">
 <div ng-controller="KhsController">
 </div>
</div>

JS

function KhsController($scope, $rootScope){
     $scope.$emit('callkhs', {param:'test'});
}
function LihatKhsController($scope, $rootScope){
    $scope.$on("callkhs", function(event, data){
      console.log('hello callkhs', data.param); //will not show
    });
}

In this scenario, KhsController will trigger LihatKhsController because LihatKhsController is the parent of KhsController.

If you use $scope.$broadcast, it will notify its child.

For instance:

<div ng-controller="KhsController">
 <div ng-controller="LihatKhsController">
 </div>
</div>

JS

function KhsController($scope, $rootScope){
     $scope.$emit('callkhs', {param:'test'});
}
function LihatKhsController($scope, $rootScope){
    $scope.$on("callkhs", function(event, data){
      console.log('hello callkhs', data.param); //will not show
    });
}

In this case, KhsController will trigger LihatKhsController as KhsController is the parent of LihatKhsController.

Both methods do not take sibling controllers into consideration.

<div ng-controller="KhsController">
</div>
 <div ng-controller="LihatKhsController">
 </div>

$emit and $broadcast have slight differences in rootScope.

Using $rootScope.$emit will only notify on $rootScope.$on.

While with $rootScope.$broadcast, it will notify both $rootScope.$on and all $scope.$on.

For example:

function KhsController($scope, $rootScope){
     $rootScope.$broadcast('callkhs', {param:'test'});
}

function LihatKhsController($scope, $rootScope){
    $scope.$on("callkhs", function(event, data){
      console.log('hello callkhs', data.param);
    });
}

Answer №2

Have you experimented with redux? It offers a contemporary approach to developing applications with consistent behavior. Additionally, there are angular bindings for redux.

Answer №3

Utilizing $rootScope.$emit instead of $rootScope.$broadcast and $rootScope.$on can provide a more direct messaging approach in AngularJS. By emitting the message from $rootScope, there is no need to cascade it down through the entire scope tree. This method may not result in significant performance improvements, but it offers a cleaner way to handle events.

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

app.controller("KhsController", function ($scope, $rootScope) {
  $scope.sendMessage = function() {
    $rootScope.$emit('message', 'message sent');
  }
});

app.controller("LihatKhsController", function ($scope, $rootScope) {
  $rootScope.$on("message", function($event, data) {
    $scope.received = data;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>

<div ng-app="khsApp">
  <form ng-controller="KhsController">
    <button ng-click="sendMessage()">Send</button>
  </form>
  <div ng-controller="LihatKhsController">
  <span ng-bind="received"></span>
  </div>
</div>

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

How can I attach an existing event to a dynamically loaded element using AJAX?

In the main page of my website, there is a button: <button class="test">test</button> Additionally, I have included the following script in my code: $('.test').on('click',function(){ alert("YOU CLICKED ME"); } ...

Adjusting iframe height dynamically across domains using Jquery

Can this task be accomplished using jQuery alone without using any bulky plugins? While I am aware of the numerous plugins and alternatives available, I am looking for the shortest, most robust, and cleanest solution (ideally utilizing jQuery). Feel free ...

Conceal the option to "show more" when there are no additional posts to display

Is there a way to dynamically hide the load button when no more posts are available? I've included my code below: function.php function load_more_posts_ajax(){ $offset = $_POST["offset"]; $ppp = $_POST["ppp"]; header("Content-Type: tex ...

Combining Array Elements to Create a Unified Object with Vue

Is there a way to transform an array into a list of objects? Transform [ { "currenttime":43481.46983805556, "moped":"30 minutes", "car":"1 hour" } ] to { "currenttime":43481.46983805556, "moped":"30 minutes", ...

What is the best way to consistently display a scroll bar at the bottom?

How can I ensure that the scroll bar is always at the bottom when loading pages? I need an immediate solution. The JavaScript code seems to be malfunctioning. Please assist me in resolving this issue. #student_name{ height:315px; } <div id ...

Manipulating arrays of objects with handlebars.js

I need help with my node.js app that is returning JSON data for computers. { computers: { john: { cpu: "intel", ram: "8MB", hd: "1TB" }, jane: { cpu: "intel", ram: "12MB", hd: "500GB" }, mary: { ...

Having difficulty retrieving the current time of an audio element using jQuery

Currently, I am facing an issue while attempting to manage an audio element for my custom player. Despite numerous attempts, I have been unsuccessful in acquiring the currentTime and duration properties. Below is a snippet of what I've tried: var pla ...

Altering the color scheme of a specific column within a stacked bar chart using C3.js

I'm currently facing a challenge with highlighting specific values in a c3.js stacked bar chart. While I was able to change the color of an individual bar in a non-stacked bar following this example, I'm struggling to determine how to identify th ...

Above the search box in jQuery Datatable's search box, there is search text displayed

My datatable looks like this: var exTable1 = $("#exTable").DataTable({ "language": { "search": "Filter", "searchPlaceholder": "search", "loadingRecords": "", }, data: datasrc "dom": '<"top"lf>rt<"botto ...

I am dynamically generating table rows and populating them with data. However, I encountered an issue with retrieving the data by their respective IDs

Creating a table row dynamically by populating it with data. However, encountering an issue with retrieving the data by their respective id. if(xmlhttp.status == 200) { var adminList = xmlhttp.responseJ ...

What could be causing my input to not activate my function?

I am having issues with my input buttons not triggering my functions. Can anyone provide some insight into this problem? <div id="windowBar"> <h3>Imagine you were a superhero...</h3> <input id="WindowClose" type="button" onclick=" ...

How can models effectively communicate with each other in AngularJS?

In my application, I have a navigation module that contains details (NavigationModel). There are also modules (SubCtrl1, SubCtrl2..) that can be selected from the Navigation part (NavigationCtrl). Each module has its own model with different properties, so ...

Navigating with Vue Router on Internet Information Services (IIS)

I am encountering difficulties understanding why my routes are failing when I refresh my VueJS application hosted on IIS. Everything works fine during normal browsing, but once I press F5 or update view information through a button, a 403 error is thrown. ...

What is the best way to retrieve a particular nested value from a fetch POST response?

I performed a POST request in this manner: var myHeaders = new fetch.Headers(); raw = "srvrwd-ui=useMe" var requestOptions = { method: 'POST', headers: myHeaders, body: raw, redirect: &a ...

steps for making a specific cell editable in tabulatorI'm happy to help

click here for image description required initializeTabulatortableBng() { let thisClass = this; let bngTableData = thisClass.tableDataWorm; function formatDecimal(cell) { var value = cell.getValue(); if (value !== null && value !== undefine ...

Refreshing the dropdown selection to a specific option using AngularJS and either JavaScript or jQuery

Currently, I am facing an issue with resetting the select tag to its first option. I have implemented Materialize CSS for styling purposes. Despite my efforts, the code snippet below is not achieving the desired outcome. Here is the JavaScript within an ...

Can Vue.js be configured to reload specific components only?

Can a specific component be reloaded in a Vue component that contains multiple components? For example, if there is a component structured like this: Main component <template> <button>Button<button> <component1></component> ...

I seem to be struggling with hiding/showing a div element. Can you figure

I am in the process of creating a gallery that will display a div with images when a button is clicked. The issue I am facing is that when I have two buttons, only the last images are clickable. It's a bit difficult to explain, but you can see it in ...

Switching from using a computed property in Vue 2 to implementing the Vue 3 Composition API

I am currently in the process of updating my Vue 2 application to Vue 3 and I have been exploring how to work with computed properties using the Composition API in Vue 3. One particular challenge I am facing is migrating a Vue 2 computed property that pro ...

What is the functionality of this.$eval in Vue.js?

During the process of updating an unfamiliar old script from version 0.11 to 2.5.4, an alert popped up stating: To address the warning message saying 'Replace this.$eval('reportData | reportFilter false') with a solution using normal Java ...