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

时间:2014-09-02 09:42:47

标签: javascript jquery angularjs

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

2 个答案:

答案 0 :(得分:9)

在您的情况下,您可以监听window.onresize事件并更改一些范围变量,这将控制模板网址,例如在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

答案 1 :(得分:6)

来自Angular Directive Documentation

  

您可以将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'
             }
        }
    }
}]);

更新:我刚看到您的更新,我认为问题可能是您使用的是角度$ window包装但未注入它。我修改了我的答案添加注入并使用$ window。

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