问题描述
我需要根据屏幕分辨率更改 templateURL,例如如果我的屏幕宽度小于 768px,它必须加载templates/browse-content-mobile.html",如果它大于 768px,它必须加载templates/browse-content.html".
I need to change the templateURL according to screen resolution, For e.g. if my screen width is less than 768px that it must load "templates/browse-content-mobile.html" if its greater than 768px it must load "templates/browse-content.html".
当前使用的代码.
app.directive('browseContent', function() {
return {
restrict: 'E',
templateUrl: template_url + '/templates/browse-content.html'
}
});
这里我正在尝试使用此代码
Here i am trying with this code
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
}
});
此代码块正在工作,它根据分辨率加载移动和桌面页面,但是当我调整页面大小时它保持不变......
This Code block is working, it loads the mobile and desktop page according to there resolution but when i resize the page it remain the same ...
例如如果我在最小化窗口(480px)中打开浏览器并将其最大化到 1366px,templateUrl 保持与/templates/browse-content-mobile.html'"相同,它必须是/templates/browse-content.html"
For e.g. if I open the browser in minimize window (480px) and maximize it to 1366px the templateUrl remain same as "/templates/browse-content-mobile.html'" it must be "/templates/browse-content.html"
推荐答案
在您的情况下,您可以监听 window.onresize
事件并更改一些范围变量,这将控制模板 url,例如在 ngInclude.
In your case you can listen window.onresize
event and change some scope variable, which would control template url, for example in 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';
}
}
}
}
});
这篇关于根据屏幕分辨率 AngularJS 更改指令的 templateUrl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!