vs7 vs7 - 5 months ago 45
jQuery Question

Change the templateUrl of directive based on screen resolution AngularJS

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".

Current used code .

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 ...

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"

Answer

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';
                }
            }
        }
    }
});

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