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">
<head>
<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 />
<script>
var MyApp = angular.module('MyApp', []);
MyApp.config(function($locationProvider){
$locationProvider.hashPrefix('!');
});
MyApp.factory('routeMapToController', function($location,$q){
var deferred = $q.defer();
var path = $location.path();
var matches = null;
if(path.match("\/issue\/(.+)\/(.+)")){
matches = path.match("\/issue\/(.+)\/(.+)");
deferred.resolve("My resolved foo!");
};
return deferred.promise;
});
MyApp.controller('MyCtrl', function($scope, routeMapToController){
$scope.foo = "Hello World!";
routeMapToController.then(function(data){
console.log(data);
});
});
</script>
</head>
<body>
<div ng-controller="MyCtrl">
<h1>{{foo}}</h1>
</div>
</body>
</html>
Thanks for looking!