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..