var app = angular.module("MyApp", []); app.controller("MyCtrl", function($scope){ $scope.state = 0; $scope.onPushState = function(){ history.pushState(++$scope.state, null, null); }; $scope.onPopState = function(state){ if(state !== null){ $scope.state = state; } }; history.replaceState($scope.state, null, null); }); app.directive("ngPopstate", function($parse, $timeout, $window){ return function($scope, $element, $attributes){ var fn = $parse($attributes["ngPopstate"]); $window.addEventListener("popstate", function(event){ event.stopPropagation(); event.preventDefault(); $timeout(function() { fn($scope, { $state : event.state, $event : event }); }); }); }; });
<body ng-app="MyApp" ng-controller="MyCtrl" ng-popstate="onPopState($state)"> <div> <button type="button" ng-click="onPushState()">pushState</button> <input type="text" ng-model="state" readonly /> </div> </body>