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

vs7*_*vs7 11 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'
    }
});
Run Code Online (Sandbox Code Playgroud)

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

 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
    }
});
Run Code Online (Sandbox Code Playgroud)

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

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

dfs*_*fsq 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';
                }
            }
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

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


Dav*_*ech 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'
             }
        }
    }
}]);
Run Code Online (Sandbox Code Playgroud)

更新:我刚刚看到你的更新,我认为问题可能是你使用angular $ window包装但没有注入它.我修改了我的答案添加注入并使用$ window.

更新2自我发布此答案以来,问题的范围已经改变.您接受的答案将回答当前问题的范围.