我必须为现有网站构建一个应用程序,但不幸的是网站(在我的控制之外)检测到用户设备并重定向到移动版本。

我试图重用相同的js文件,但不同的html文件。

所以我有:

  1. 索引。桌面html
  2. 移动。移动html

两者都调用init。js在我想处理我的逻辑的地方,我的问题是由于某种原因路由没有像我预期的那样工作,我无法弄清楚为什么。

桌面版:

  1. 我去example.com
  2. 重定向到example.com/#/steps/age/0
  3. 刷新页面,它停留在example.com/#/steps/age/0

这按预期工作

流动电话:

  1. 我去example.com/mobile.html
  2. 重定向到example.com/mobile.html#/steps/age/0
  3. 刷新页面,而不是停留在同一个url,它转到example.com/steps/age/0#/steps/age/0

这不按预期工作(预期在刷新后保持在相同的url中,如步骤编号2中所示)

代码如下:

angular
.module('profileToolApp', ["ngRoute", "ngResource", "ngSanitize"])
.config(function($routeProvider, $locationProvider){
    $routeProvider
    .when('/steps/:steps*', {
        templateUrl : 'profile-app.html',
        controller : 'example'
    })
    .otherwise({
        redirectTo: '/steps/age/0'
    });
})
.controller('example', function($scope, $routeParams, $resource, $location){
    console.log("example controller");
});

任何人都可以请指教?谢谢.

有帮助吗?

解决方案

Angular正在检查整个路径,看看它应该路由到哪里。所以当你有 example.com/mobile.html#/steps/age/0 没有匹配的路线,所以它代替你的路线,代替 mobile.html 所以你得到了 /steps/age/0#/steps/age/0 从你的 otherwise.根本的问题是angular没有任何意义 mobile.html 表示,并将其作为参数。

一种解决方案是使用路由来分离您的页面。

$routeProvider
    .when('/', {
        templateUrl : 'desktop.html', //was 'index.html pre edit
        controller : 'example'
    })
    .when('/mobile/', {
        templateUrl : 'mobile.html',
        controller : 'example'
    })
    .when('/steps/:steps*', {
        templateUrl : 'profile-app.html',
        controller : 'example'
    })
    .when('/mobile/steps/:steps*', {
        templateUrl : 'mobile-profile-app.html',
        controller : 'example'
    })
    .otherwise({
        redirectTo: '/'
    });
})

控制器可以根据需要而变化。

替代这一点是有 mobile.html 使用自己的angular应用程序和路由,这可能是有益的,因为您不会遇到泄漏到移动端的桌面指令。您可以将所有指令和控制器注入其中,但仍然有一个很好的索引和移动分离。你可以更进一步,重定向到 m.example.com, ,但那是一个不同的话题。

编辑 我犯了个错误有 templateUrlindex.html 有点不对。 index.html 应包含您的 ng-app 而你的 ng-view 指令,可能是控制器。任何常见的html都应该驻留在那里。 desktop.htmlmobile.html 应包含这些平台的特定HTML。

作为事后的想法,在那些你可以有一个指令叫 profile 这就完成了你所有的个人资料工作,并且有一点 ng-switch 你可以有出现,如果 steps 被定义在范围内,并使用:

$routeProvider
.when('/steps?/:steps?', {
    templateUrl : 'desktop.html', //was 'index.html pre edit
    controller : 'example'
})
.when('/mobile/steps?/:steps?', {
    templateUrl : 'mobile.html',
    controller : 'example'
})

但现在我漫无目的,我不是100%确定这将工作tbh。 结束编辑

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top