AngularJS different views based on Desktop or Mobile

后端 未结 6 1980
梦毁少年i
梦毁少年i 2020-12-07 09:09

I would like to use AngularJS for a single page webapp. I am concerned if there is an elegant way to \"send\" different templates based on whether the client is

6条回答
  •  情深已故
    2020-12-07 09:25

    A bit late, but in something like your header, or nav controller, you could set the initial width:

    angular
        .module('myApp')
        .controller('navCtrl', ['$rootScope', '$window',
            function($rootScope, $window) {
                $rootScope.is_mobile = ($window.innerWidth < 480);
    

    And if you want checking on resize, go ahead and bind it:

    angular.element($window).bind('resize', function() {
        $scope.$apply();
    });
    

    Then watch it:

    $scope.$watch(function () {
        return $window.innerWidth;
    }, function (innerWidth) {
        $rootScope.safeApply(function () {
            $rootScope.is_mobile = innerWidth < 480 // went with max device width
        });
    });
    

    Then in your HTML:

    Show me only in mobile

提交回复
热议问题