簡體   English   中英

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

[英]Change the templateUrl of directive based on screen resolution 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”

在您的情況下,您可以監聽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指令文檔

您可以將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自我發布此答案以來,問題的范圍已經改變。 您接受的答案將回答當前問題的范圍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM