Force angle to reanalyze ngClass when the width of the screen changes

0

I'm building an application where I depend on ngClass to change the class of elements. The problem is that I can not get ngClass to interpret a change in screen width (concept of responsiveness).

I know I can do this by using $scope.$watch in another directive but I want to keep the maximum control already native to AngularJS. Is there any way to make ngClass identify that there was a change in page width and reassess its condition?

    
asked by anonymous 06.08.2016 / 04:03

1 answer

4

You can set the following function within .run

.run(function($window, $timeout, $rootScope) {
    var timer;

    function verificaTela() {
        var width = $window.innerWidth;

        if(width < 600) {
            $rootScope._isMobile = true;
        } else {
            $rootScope._isMobile = false;
        }
    }

    //Chama a função quando mudar o tamanho da tela
    angular.element($window).on('resize', function() {
        $timeout.cancel(timer);
        timer = $timeout(verificaTela, 600);
    })

    //Chama a função no primeiro load
    verificaTela();
});

I'd rather declare within .run because it runs right at the beginning of the application, so when your DOM starts to be structured, the value will already be available.

Then you just have to do the checks with ngClass , for example:

<div ng-class="{'classeMobile': _isMobile}"></div>

//ou assim
<div ng-class="_isMobile ? 'classeMobile' : 'classeDesktop'"></div>
    
06.08.2016 / 04:32