$ watch for location.hash更改

时间:2015-05-24 12:29:19

标签: angularjs

在我的角度应用中,当用户输入无效路线时,我会尝试将位置更改为"#home"

这是一个简短但完整的应用程序,展示了我的所作所为。

<!DOCTYPE html>
<html>
<head>
    <script src="angular.js"></script>
    <script>
        angular.module('app', [])
        .controller('ctrl', function($scope, $location, $window) {
            $scope.$watch (function() { return $location.url() }, function(url) {
                if (url == '')
                    $window.location = '#home'
            })
        })
    </script>
</head>
<body ng-app="app" ng-controller="ctrl"></body>
</html>

但是当我这样做时,页面加载时出现infdig错误。我不知道什么是错的。

修改 我不想使用像“ui-router”这样的路由库。所以使用“角度路线”库的this one之类的答案没有帮助。

1 个答案:

答案 0 :(得分:2)

您可以使用app.config$routeProvider块中指定。

app.config(function ($routeProvider) {
  $routeProvider
    .when('/home', {
      template: 'home.html',
      controller: 'homeController'
    })
    .otherwise('/home');
});
如果用户尝试访问未在config中指定的任何无效路径,

.otherwise方法会将应用程序重定向到/home

<强>更新

并且,如果您不想使用角度路由库,则可以在窗口上使用本机javascript事件hashchange来侦听哈希更改事件。并相应地重定向。

见下面的例子。

function locationHashChanged() {
  if (location.hash !== "#/home") {
    console.log('hash is other then #home. will redirect to #home');
    console.log('Full path before', document.URL);
    window.location.hash = '#/home';
    console.log('Full path after', document.URL);
  }
}

window.addEventListener('load', locationHashChanged);
window.addEventListener('hashchange', locationHashChanged);
<a href="#home">Home</a>
<br/>
<a href="#somesite">Some-Site</a>
<br/>
<a href="#other">Other</a>