问题 根据屏幕分辨率AngularJS更改指令的templateUrl


我需要根据屏幕分辨率更改templateURL,例如如果我的屏幕宽度小于768px,它必须加载“templates / browse-content-mobile.html”,如果它大于768px,它必须加载“templates / browse-content.html”。

当前使用的代码。

app.directive('browseContent', function() {
    return {
        restrict: 'E',
        templateUrl: template_url + '/templates/browse-content.html'
    }
});

在这里,我尝试使用此代码

 app.directive('browseContent', function() {
    screen_width = window.innerWidth;
    if (screen_width < 768) {
        load_tempalte = template_url + '/templates/browse-content-mobile.html';
    } else if (screen_width >= 768) {
        load_tempalte = template_url + '/templates/browse-content.html';
    }
    return {
        restrict: 'E',
        templateUrl: load_tempalte
    }
});

此代码块正在运行,它根据分辨率加载移动和桌面页面但是当我调整页面大小时它保持不变...

对于例如如果我在最小化窗口(480px)中打开浏览器并将其最大化为1366px,则templateUrl保持与“/templates/browse-content-mobile.html”相同,它必须是“/templates/browse-content.html”


1398
2017-09-02 09:42


起源

我使用了window.innerWidth工作正常... - vs7
您应该使用媒体查询来执行此任务。 - dfsq
@dfsq不能像我们在jQuery中那样使用.resize()...它不是来自布局的差异......否则我会使用css媒体查询......两个文件都有不同的功能和设计 - vs7
是的,在这种情况下,媒体查询是不够的。用.resize事件检查我的答案。 - dfsq


答案:


在你的情况下你可以听 window.onresize 事件和更改一些范围变量,它将控制模板URL,例如在 ngInclude

app.directive('browseContent', function($window) {
    return {
        restrict: 'E',
        template: '<div ng-include="templateUrl"></div>',
        link: function(scope) {

            $window.onresize = function() {
                changeTemplate();
                scope.$apply();
            };
            changeTemplate();

            function changeTemplate() {
                var screenWidth = $window.innerWidth;
                if (screenWidth < 768) {
                    scope.templateUrl = 'browse-content-mobile.html';
                } else if (screenWidth >= 768) {
                    scope.templateUrl = 'browse-content.html';
                }
            }
        }
    }
});

演示: http://plnkr.co/edit/DhwxNkDhmnIpdrKg29ax?p=preview


9
2017-09-02 10:30



它似乎工作......我一次又一次地对每个调整大小角度请求页面有一个疑问? - vs7
我有同样的疑问。在Chrome中,调整大小只会触发一次,我不确定其他浏览器。我会在这里实现节流机制。 - dfsq
如果它发生它将挂断浏览器......我还检查了chrome和firefox它的唯一请求一次...... - vs7
我已经检查过IE,Chrome和Firefox的工作正常并请求一次感谢好友:) - vs7


来自 角度指令文档

您可以将templateUrl指定为表示URL的字符串或作为   函数有两个参数tElement和tAttrs。

因此,您可以将指令定义为

app.directive('browseContent', ['$window', function($window) {
    return {
        restrict: 'E',
        templateUrl: function(tElement, tAttrs) {
             var width = $window.innerWidth;  //or some other test..
             if (width <= 768) {
                 return 'templates/browse-content-mobile.html';
             } else {
                 return '/templates/browse-content.html'
             }
        }
    }
}]);

更新: 我刚看到你的更新,我认为问题可能是你正在使用angular $ window wrapper而不是注入它。我修改了我的答案添加注入并使用$ window。

更新2 自从我发布这个答案后,问题的范围发生了变化。您接受的答案将回答当前问题的范围。


6
2017-09-02 09:53



我已经更新了这个问题,请看一下 - vs7