What is the best way to respond to a hashchange event within AngularJs?

I am new to AngularJs and I am trying to update the page on hashchange events.

Currently, I have this code which I know is not the proper way to do it:

<!DOCTYPE html>
<html>
<head>
<style>
    #hashdrop {
      display:block;
      border: 1px solid gray;
      width: 500px;
      overflow: auto;
      background-color: rgb(241,241,241);
      border-radius: 4px;
      text-align: center;
      vertical-align: middle;
      line-height: 100px;
      font-size: large;
      height: 100px;
    }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script>
    var example = function($scope) {
      $scope.lastHash = location.hash.slice(1);
      $(window).on('hashchange', function (event) {
        $scope.lashHash = location.hash.slice(1);
        $scope.$apply();
      });
    };
</script>
<meta charset=utf-8 />
</head>
<body ng-app ng-controller="example">
  <div id="hashdrop" >
    {{lastHash}}
  </div>
</body>
</html>

(You can copy and paste this into a blank HTML file and run it. For me, jsbin didn't detect the haschange correctly)

This approach doesn't seem to work as expected. I believe there must be a better way to achieve this in AngularJS.
I would appreciate understanding the correct way to do this in AngularJS and specifically how to modify the code in this example to follow best practices.

Thank you!

UPDATE 1 After learning about $location from a comment, I made some changes to my code like so:

<!DOCTYPE html>
<html>
<head>
<style>
    #hashdrop {
      display:block;
      border: 1px solid gray;
      width: 500px;
      overflow: auto;
      background-color: rgb(241,241,241);
      border-radius: 4px;
      text-align: center;
      vertical-align: middle;
      line-height: 100px;
      font-size: large;
      height: 100px;
    }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script>
    angular.module('example',[]).config(function($locationProvider, $routeProvider) {
      $locationProvider.html5Mode(true);
    });
    var example = function($scope, $location) {


    };
</script>
<meta charset=utf-8 />
</head>
<body ng-app="example" ng-controller="example">
  <div id="hashdrop" >
    Hash = {{$location.hash()}}
  </div>
</body>
</html>

It's still not working. Nothing is displaying in the output..

Answer №1

When it comes to navigating pages in AngularJs, the use of hashes in URLs is standard practice. By utilizing routeProvider, you can define URL schemas similar to those found in backend MVC frameworks like Django. This allows routeProvider to monitor changes in the hash and load new content accordingly.

I highly recommend following the tutorial as it provides a solid foundation, despite not covering everything. You can find demonstrations of routes in step 7.

One important aspect to note is that Angular expects the primary method for managing URLs and routing to be through hashes. This means that routeParams will not allow you to modify only a portion of a page when altering the hash section of the URL. If this is necessary, consider switching to using GET parameters or exploring alternatives like ui-router for increased flexibility.

Answer №2

If you're looking to reduce dependencies, consider binding to the hashchange event using angular.element instead of relying on jQuery.

To implement this in your controller, add the following code:

angular.element(window).bind('hashchange', function() {
  console.log('hash has changed');
});

With this code in place, "hash has changed" will be logged whenever the hash is altered.

While this approach may not fix all issues (as Kevin Beal pointed out potential discrepancies in your code), it can help address some challenges. If you prefer using jQuery, keep in mind that angular.element defaults to jQuery when available. In such cases, using angular.element(window) or $(window) would yield similar results.

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

Troubleshooting the issue with the htmlFor attribute

I have encountered an issue with creating radio buttons and labels using JavaScript. Despite adding the 'for' attribute in the label using 'htmlFor', it does not apply to the actual DOM Element. This results in the label not selecting t ...

What are the Functions of Ctrl-K on Stack Overflow?

I'm intrigued by how to incorporate the Ctrl+K (code sample) feature for code. For example: public static void main(String args[]){ System.out.println.out("welcome"); } Is there a way to nicely format this? Do we need any specific package to ...

I am interested in implementing a logout feature using a button in PHP

<?php session_start(); ?> <form> <input type="button" id="logout" value="logout" name="logout"> </form> After initializing the session during login, I am seeking to terminate it using a button rather than via <a href="">l ...

What is causing my checkboxes to deactivate other selections?

My checkboxes are causing a dilemma where changing the value of one checkbox sets all others to false. To address this issue, I am considering implementing a solution in my validate.php file that would only update the intended checkbox value. If this appro ...

Using Angular Directive to create a customized TreeView

Although I am still relatively new to Angular, I need to make some modifications to a treeview directive that I found on NgModules. The existing code looks promising, but I want to customize it to include the ability to add, delete, or modify items. You c ...

What exactly is the functionality of the third parameter (usually next()) behind the scenes in ExpressJS once it is hidden behind the abstraction layer?

Consider this scenario: in the following two code snippets, how is the next() function used as a parameter and how does it facilitate the automatic transition to the next middleware function? What is the underlying mechanism that enables this abstraction? ...

I am interested in discovering the optimal method for loading a vehicle to its maximum capacity by exploring various combinations

My current task involves developing an algorithm to optimize the filling of a vehicle to its capacity based on various input combinations. Although the core problem has been resolved, the algorithm's efficiency is inadequate when dealing with a higher ...

Best practice for sending a Facebook token securely between client and server

I'm facing a dilemma on how to securely transfer a user's Facebook token from their client to my server. Currently, I have the following approach in mind: The user accesses a webpage and logs in to Facebook; Facebook token is obtained; User&apo ...

Minimizing conditional statements in my JavaScript code

I've just completed the development of a slider and am currently working on optimizing some repetitive if/else statements in the code. The purpose of these conditions is to determine whether the slider has reached the last slide, in which case the nex ...

What is the best way to position an image in the bottom right corner of a fluid div container?

I am struggling to position this icon image at the bottom right hand corner of this div, so that it appears as if the message is originating from the icon's head. Despite my efforts, I have yet to find a definitive solution. https://i.stack.imgur.com ...

An error occurred while trying to load the resource in the Redux-Saga: connection refused

Utilizing axios allows me to make calls to the backend server, while redux-saga helps in managing side effects from the server seamlessly. import {call, put, takeEvery} from "redux-saga/effects"; import {REQUEST_FAILED, REQUEST_SUCCESS, ROOT_URL, SUBMIT_U ...

What techniques can I use to achieve a seamless transition using Javascript and CSS?

I'm striving for a seamless CSS transition. The concept of transition had me puzzled. Even though I utilized the setTimeout method in JavaScript to make my CSS functional, it lacks that SMOOTH feel! Check out my code below. function slideChange( ...

Ways to conceal road labels on ng-map

I am in the process of building a simple map using ng-Map and I would like to conceal the names of all roads and streets. Is there a way to achieve this? ...

transmitting JSON content type as opposed to displaying a webpage

Here is the code snippet I am working with: router.get('/findRecord', authCheck, (req, res) => { let amountOfTokens = req.session.amountOfTokens request.post({ url: 'https://myurl.com/user_records', headers: { " ...

What is the reason for the Client Height value not affecting other elements?

I'm trying to set the spacing of my sidebar from the top equal to the height of the header. However, when I use clientHeight in JavaScript to get the height and then try to apply it to other elements using marginTop or top values (with position includ ...

Is it possible to prevent copying dates within tabs using Angular-UI Bootstrap?

I have set up a basic Tab using Angular-ui bootstrap. Within the tab, there is a 'date input' <input type="date"/> <tabset> <tab heading="Tab A"> Date Input Inside Tab</br> Date 1:<input type="dat ...

Is there a method to create a typecheck for hasOwnProperty?

Given a certain interface interface Bar { bar?: string } Is there a way to make the hasOwnProperty method check the property against the defined interface? const b: Bar = { bar: 'b' } b.hasOwnProperty('bar') // works as expected b. ...

How can I retrieve and process a text or .csv file that has been uploaded using Multer?

Just starting out with Multer - I created an application to analyze a .csv file and determine the frequency of each keyword and phrase in the document. However, I have since made adjustments using node and express to analyse the file AFTER it has been subm ...

Retrieve the value of a selected element

I currently have an HTML select drop down that is populated by a JQuery get request. You can see this in action at this link. My goal is to access the specific piece of code for the selected value every time it changes. <small class="text-muted"> ...

Alert: The lack of boundary in the multipart/form-data POST data has been detected in an unknown source on line

I am currently developing a file uploader that uploads an image when the input changes. Here is the code for my HTML form: <form method="post" enctype="multipart/form-data"> <input name="uploaded[]" type="file" id="file_upload"/> </for ...