Change view based on screen size

I know the question that was asked before:

Change templateUrl directives based on AngularJS screen resolution

This was first asked over a year ago, and since then AngularJS has changed a bit. I am curious to find out if there are other ways to achieve something similar, since I did not find much information about the exchange of templates, so maybe I am barking the wrong tree here.

I have a single page application without any routes.

HTML:

<body ng-app="App">
  // lots of html same for both desktop/mobile
  <my-dir></my-dir>
  // even more here
</body>

pattern 1:

<p>Mobile</p>

pattern 2:

<p>Desktop</p>

I would like to make pattern 1 when the screen is below 700px and pattern 2 . Templates change what is inside the my-dir directive . For example, template 1 displays a list and template 2 displays a table.

, ( )

, ?

+4
2

:

$scope.includeDesktopTemplate = false;
$scope.includeMobileTemplate = false; 
var screenWidth = $window.innerWidth;

if (screenWidth < 700){
    $scope.includeMobileTemplate = true;
}else{
    $scope.includeDesktopTemplate = true;
}

html template:

<body ng-app="App">
    <p ng-if="includeMobileTemplate">Mobile</p>
    <p ng-if="includeDesktopTemplate">Desktop</p>
</body>

,

+6

my-dir:

angular.module("App").directive('myDir', ['$window', '$timeout', function($window, $timeout){

    return {
        restrict: 'EA',
        scope: {},
        template:'<div>
            <p ng-if="showFirstTemplate">Mobile</p>
            <p ng-if="showSecondTemplate">Desktop</p>
            </div>',
        link: function(scope, element, attr){

            function checkTemplateVisible(event){

                 //use $timeout to make sure $apply called in a time manner
                 $timeout(function(){

                      //pageYoffset is equal to window scroll top position
                      if($window.pageYOffset > 700){
                          scope.showFirstTemplate = true;
                          scope.showSecondTemplate = false;
                      }else{
                          scope.showFirstTemplate = false;
                          scope.showSecondTemplate = true;
                      }
                 })

            })

            //scroll event make sure checkTemplateVisible called on browser scrolling
            $window.on('scroll', checkTemplateVisible)

            //resize event make sure checkTemplateVisible called on browser resizing
            $window.on('resize', checkTemplateVisible)
        }
    }


}])
+4

Source: https://habr.com/ru/post/1612920/


All Articles