Last Updated: February 25, 2016
· heldrida

AngularJS, monitor location.hash and call function on match


I'm quiet newbie with AngularJS so I've been amazed with how complex but useful all it's features can happen to be. The last one was on how to use the route mapper to solve one requirement in my Single Page App: I need to map a location.hash to a function, but AngularJS that doesn't really work as Backbone. AngularJS maps it to a view and a controller. So, for the cases where you'd like to trigger an animation, scroll to a position in the page or expand a given element, it's not useful!

I came up with this, but take extra notice and take it with scepticism. It's just a prototype but I guess that the idea is pretty clear and I hope it helps solving your problems.

<!DOCTYPE html>
<html ng-app="MyApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<meta charset=utf-8 /> 
var MyApp = angular.module('MyApp', []);


MyApp.factory('routeMapToController', function($location,$q){

    var deferred = $q.defer();
    var path = $location.path();
    var matches = null;

        matches = path.match("\/issue\/(.+)\/(.+)");
        deferred.resolve("My resolved foo!");

    return deferred.promise;

MyApp.controller('MyCtrl', function($scope, routeMapToController){
  $scope.foo = "Hello World!";
  <div ng-controller="MyCtrl">

Thanks for looking!

Say Thanks