根据屏幕分辨率改变指令的templateUrl AngularJS

11

我需要根据屏幕分辨率更改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
    }
});

这段代码块是有效的,它会根据移动设备和桌面设备的分辨率来加载相应的页面。但是当我调整页面大小时,它仍然保持不变...

例如,如果我将浏览器在最小化窗口(480像素)中打开,然后将其最大化到1366像素,templateUrl仍然保持为“/templates/browse-content-mobile.html”,而应该是“/templates/browse-content.html”


我已经使用了window.innerWidth,它运行良好... - vs7
你应该使用媒体查询来完成这个任务。 - dfsq
@dfsq我们不能像在jQuery中那样使用.resize()吗?这与布局没有什么不同...否则我会使用CSS媒体查询...这两个文件具有不同的功能和设计。 - vs7
是的,在这种情况下,媒体查询并不足够。请检查我的回答和调整大小事件。 - dfsq
2个回答

9
在您的情况下,您可以侦听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

似乎正在工作... 我有一个疑问,每次调整大小时,Angular 是否会重新请求页面? - vs7
我有同样的疑问。在Chrome中,调整大小只会触发一次,其他浏览器我不确定。我会在这里实现节流机制。 - dfsq
如果发生这种情况,它会挂起浏览器...我也在Chrome和Firefox中进行了检查,它只请求一次... - vs7
我已经检查了IE,Chrome和Firefox,它们都正常工作,并且请求一次,谢谢伙计 :) - vs7

6

根据Angular指令文档:

您可以将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包装器但没有注入它。我修改了我的答案以添加注入并使用$window。

更新2:自从我发布这个答案以来,问题的范围已经发生了变化。你已经接受的答案回答了当前问题的范围。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接