Is there a way for me to determine if the routeChangeStart event was triggered by JavaScript or a user click?

Exploring Main.js

$routeProvider
    .when('/home', {
        templateUrl: 'home.html',
        controller: 'StudentController'
    })
    .when('/viewStudents', {
        templateUrl: 'viewStudents.html',
        controller: 'StudentController'
    })
    .when('/viewTeacher', {
        templateUrl: 'viewTeacher.html',
        controller: 'StudentController'
    })
    .otherwise({
        redirectTo: '/home'
    });

Code within another JavaScript file

   $rootScope.$on("$routeChangeStart", function(event, next, current){
                console.log(event);
                //detecting action here         
            });

When a user visits index.html, the home route is triggered from JS and home.html is added to the view

.otherwise({
            redirectTo: '/home'
        });

There is a button that calls viewStudents.html, then the route changes and viewStudents.html is rendered

How can I determine in the routeChangeStart function whether the route change was initiated by JavaScript or by a click from the user?

Answer №1

routeChangeStart event can be triggered by either '$rootScope.$emit' or $rootScope.$broadcast

The purpose of this event system is to pass data from child controller to parent.

When you call the broadcast event, the $on event will be triggered.

It only gets called once when your controller loads, and you can also trigger it externally using a function.

    app.controller('ChildCtrl',
      function ChildCtrl ($rootScope) {

      $rootScope.$emit('rootScope:emit', 'Emit!'); // $rootScope.$on
      $rootScope.$broadcast('rootScope:broadcast', 'Broadcast'); // $rootScope.$on && $scope.$on

    });

app.controller('ParentCtrl',
  function SiblingOneCtrl ($rootScope) {
    var myListener = $scope.$on('child', function (event, data) {
        // do something
      });
    });

app.controller('ParentCtrl',
  function ParentCtrl ($scope) {

    var myListener = $rootScope.$on('child', function (event, data) {
        // do something
      });
});

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

Triggering form submission through JavaScript by simulating keypress Enter does not work

Looking to incorporate some jQuery script into a website featuring keyword searching. I've encountered an issue where, upon inserting the code below into amazon.com to designate a keyword and simulate pressing the enter key using jQuery, the form fail ...

Skipping the validation of a variable in a return statement with Angular and Javascript

Is there a way to exclude level a.3 from the return in the completion form if a.3 is undefined? scope.isValid = function() { return a.1 && a.2 && a.3; }; ng-disabled="!isValid()" ...

The Angular index value cannot be found

While working on my app, I encountered an issue where the index returned as undefined after a successful delete operation. This prevented the item from being removed from the list. Code HTML <div *ngIf="groups.length>0"> <ion-item-slidin ...

What is the best way to integrate SVGs into a React project after transitioning from Vanilla JavaScript?

I am currently diving into an Advanced CSS course that explores the implementation of SVG's. However, the approach involves Vanilla JS whereas I aim to incorporate it into a React project. When using Vanilla JS to embed an SVG into a button, you typi ...

JavaScript error: Resource could not be loaded

When I have a js function called by an onclick event in a radio button, it doesn't work if the function is placed in the same ascx file where the radio button is defined. To resolve this issue, I moved the function to the ascx that includes the ascx w ...

Proper method for handling ajax response without relying on the success handler

Similar Question: How can I make a jQuery AJAX request synchronous? Waiting for an Ajax response Let me explain my perspective. I have a good grasp on this particular code snippet. $.getJSON(someURL, function(data){ //do something with the re ...

What steps can I take in Chrome to troubleshoot and identify the root cause of this code malfunction?

How can I troubleshoot why this code isn't functioning correctly on this specific page: The objective is to remove the element if it is empty. ...

Master the art of manipulating tags in Django templates using JavaScript

In my Django quiz app, there are two main components. The first part involves displaying 10 sentences with corresponding audio to help with memorization, one per page. The second part consists of asking questions based on the same set of sentences. I initi ...

Display and conceal HTML elements depending on a condition without utilizing a div tag

I'm currently developing an Angular JS project that features three radio buttons. The code snippet is displayed below: <div class="sys-form__field" layout="row"> <label class="sys-label sys-label--radio" flex flex-gt-xs="33">C ...

Error in ElectronJS: Trying to access properties that are not defined (specifically 'whenReady')

Below is a straightforward code snippet: function myFunction() { const { app, BrowserWindow } = require('electron') const createWindow = () => { const win = new BrowserWindow({ width: 800, height: 600 ...

Is it possible to translate the content of the page into English and French simply by clicking on the designated buttons?

As I dive into working with knockout, I am still in the learning process. Currently, I have a dropdown code where selecting English translates the entire page to English and selecting French translates it to French without any issue. I believe this functio ...

Ignoring break lines in Javascript using regular expressionsKeeping break lines at bay with regular expressions

I need help modifying a regular expression to prevent users from inserting special characters like $ # ?. The current expression I am using is /^((?![#$%^*<>{}!=|/?])\s.)*$/ When I apply this expression on a textarea, Angular throws an error w ...

Typescript: Defining the correct return type for resolved parameters in promises

Exploring the world of TypeScript, I recently attempted to convert some basic JavaScript promise samples into TypeScript promises. While working on this conversion process, I encountered an issue that has left me puzzled and unable to find a solution even ...

Transmit data to PHP servers

When the button in my HTML is clicked, it should trigger a query in a PHP file that will display the results. However, the button does not seem to be working as expected. What could be causing this issue? Here is the code I have tried: <?php $reply_ ...

How can we use the nth-of-type selector to target a set of eight elements in a

I am trying to style a group of divs in such a way that every set of eight elements will have the same left positioning. Rather than just styling every eighth element individually, I want to apply the styling to groups of eight elements at once. However, ...

What is the best way to specify the CSS :hover state within a jQuery selector?

I am trying to change the background color of a div element when hovered using jQuery, but for some reason the following code is not working as expected: $(".myclass:hover div").css("background-color","red"); Can someone provide guidance on how to achiev ...

The "Overall Quantity" of items will vary as it goes through different numerical values, despite the fact that I employed --

I am currently working on an e-commerce website with a shopping cart feature. The cart displays the number of items added to it, which increases by one when 'Add to Cart' is clicked and decreases by one when 'Remove' is clicked. However ...

Only switch a radio button when the Ajax call results in success

Within an HTML form, I am working with a group of Radio buttons that trigger an Ajax call when the onchange() event is fired. This Ajax call communicates with the server to process the value sent by the call. The response can either be a string of "succes ...

Showcasing a graphical representation with the help of Highcharts

I am currently exploring JavaScript and trying to familiarize myself with interactive charts using the HighCharts library. Unfortunately, I have been facing some challenges in getting the graph to print correctly. Despite attempting various examples, none ...

The changing perspective in relation to the current position of a background

I am currently working on implementing a parallax effect, which is mostly successful. However, I have encountered a minor issue. Instead of the parallax effect being relative to the element's current position, it abruptly jumps to position 0. How can ...