使用角度路由和往返路由

时间:2013-06-26 11:25:44

标签: angularjs url-routing

我正在开发一个Django应用程序,它在某些页面中大量使用Angular,例如在domain.com/myAngularApp

在角度页面中,我使用Angular路由在该页面内的不同视图/状态之间导航。但是在整个网站上都有导航链接,这些链接需要导致对Django的往返请求。但是,所有页面都包含相同的已编译的javascript文件,其中包含Angular路由声明。

所以我的问题是:如何让Angular管理自己的路由,并在位置发生变化时(主要是通过点击页面上的链接)到一条未被明确告知的路径时离开拥有,即离开域名的不同子目录。

我的路由声明类似于:

myApp.config( function($locationProvider, $routeProvider) {
  $locationProvider.html5Mode(true);
  $routeProvider.when('/myAngularApp/', {
    templateURL: 'template1.html'
  });
  $routeProvider.when('/myAngularApp/stuff', {
    templateURL: 'template12.html'
  });
  $routeProvider.otherwise({redirectTo:  <not sure what to do here...>  });
})

我尝试过类似的事情:

$routeProvider.otherwise({redirectTo: function(a1,r,a3){ window.location.href = r }})

但这会使页面在任何不匹配的路径上无休止地刷新。

如果直接访问,则抛出else语句似乎不可能让页面留下不匹配的路径...不明白为什么?

必须可以做我想做的事吗?

1 个答案:

答案 0 :(得分:4)

我想我可能找到了解决方案。我正在做一个类似的事情,一个多页角度的网站,它使用角度的一些页面。这就是我正在做的事情

var app = angular.module('appname', ['ui.bootstrap', 'ui.autocomplete'])
.config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
    $locationProvider.html5Mode(true);
    $locationProvider.hashPrefix('!');
}])
.run(function($rootScope, $location) {
    var redirected = false;
    $rootScope.$on('$locationChangeStart', function(event, nextLocation, currentLocation) {
        if(!redirected &&  $location.path() !== '/current-url') {
            redirected = true;
            event.preventDefault();
            window.location = $location.path();
        }
    });
});

接下来我要解决的是如何传入current-url路径。我想的一种方法是使用ng-init在视图中设置数据(我使用的是express.js,所以我使用Jade)。或者可能在run函数中抓取初始路径并对其进行测试。

event.preventDefault()用于停止添加到浏览器历史记录中的额外项目。在我这样做之前,我必须回击两次以回到角度页面。

注意尚未使用IE8测试过。我现在要去做,看看它是如何展开的。

更新好的,我刚刚在IE8中对此进行了测试,但我陷入了重定向循环。我已经更新了代码以获得一个简单的变量来检查我们是否已重定向。似乎工作。我想知道更漂亮的方式。