【问题标题】:AngularJS: Use different templates for desktop and mobile?AngularJS:为桌面和移动使用不同的模板?
【发布时间】:2016-01-03 21:00:50
【问题描述】:

对于 AngularJS 应用程序中的任何给定路由或状态,我希望可以选择使用特定于移动设备或特定于桌面的模板,具体取决于用户的设备。我还希望用户能够选择哪个版本(桌面版或移动版),而不管他们使用的是什么设备。

具体来说,我想要一个单独的模板,因为在许多情况下,单独的模板比使用响应式设计要简单得多。

有没有一种简单的方法可以做到这一点?

这是我想做的,但我不知道如何使用 angular-ui-router 使 templateUrl 函数可以访问“isMobile”变量。任何帮助将不胜感激。

angular
    .module('app.items', [])
    .config(config);

function config($stateProvider) {

    //$window service not available in config block, so how can I set this variable?
    var isMobile = $window.sessionStorage.getItem('isMobile'); 

    $stateProvider

    .state('itemsList', {
        url: '/items',
        templateUrl: function($stateParams) {

            if (isMobile) {  //How do I get this information (variable) in here?
                return 'app/items/list.mobile.html';
            }
            else {
                return 'app/items/list.desktop.html'
            }

        },
        controller: 'ItemsListController'
    });

}

【问题讨论】:

  • isMobiletemplateUrl 函数内部可用。您是否尝试运行您的代码?
  • 我知道它成功地从上面引用了 var isMobile,但是如何从 $window.sessionStorage 这样的“全局”位置进行设置?

标签: angularjs angular-ui-router


【解决方案1】:

您可能只想通过 angular 并使用本机 window.sessionStorage,或者如果您想让您的用户保存首选项,window.localStorage。无论如何, $window 服务本质上只是一个包装器。

【讨论】:

  • 这样更容易实现,但更难进行单元测试。
【解决方案2】:

您可以使用常量来设置它(假设您可以在应用程序启动之前处理常量值)。

angular.module('app.items')
    .constant('isMobile', window.sessionStorage.getItem('isMobile'));
    .config(['$injector', function($injector) {
        var $stateProvider = $injector.get('$stateProvider'),
            isMobile       = $injector.get('isMobile');
    ]});

编辑以允许用户切换模板

如果您想允许用户进行选择,我建议您创建一个工厂来获取/设置该值。

angular.module('app.items')
    .factory('isMobile', [function() {
        return {
            get: function() { return $window.sessionStorage.getItem('isMobile'); },
            set: function(bool) { $window.sessionStorage.setItem('isMobile', bool); }
        };
    }]);

然后在你的$stateProvider

angular.module('app.items')
    .config(['$stateProvider', function($stateProvider) {
        $stateProvider
            .state('itemsList', {
                url: '/items',
                templateUrl: ['$stateParams', 'isMobile', function($stateParams, isMobile) {
                    if (isMobile.get()) { return '/mobile/template.html'; }
                    else { return 'desktop/template.html'; }
                }],
                controller: 'ItemsListController'
            });
    }]);

更新只会在使用此方法的状态更改时发生,但您可以在isMobile.set 上执行一些会强制更改的任务。

【讨论】:

  • 我如何允许用户选择移动或桌面网站,而不管他们使用这种预引导技术的设备是什么?
  • 我在原始答案中没有考虑到这一点。我已经更新了我的答案,改为使用工厂。
  • 我猜这只是语义,但我决定不建议一个常量,因为该值不是常量,而是由用户选择控制。
  • 这很接近,但 templateUrl 部分不起作用。请参阅此答案以动态加载模板:stackoverflow.com/a/25596163/6997327
猜你喜欢
  • 2019-07-30
  • 2014-06-19
  • 2021-07-25
  • 2013-04-24
  • 2018-11-11
  • 2011-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多