Search code examples
angularjscarouselangular-ui

Change attribute after resize ? AngularJS


I use angular-ui carousel ,and my directive now looks like this

<ui-carousel slides="value" 
             slides-to-show="calculateGamesCount"
             slides-to-scroll="calculateGamesCount"> 
      ... 
</ui-carousel>

Directive scope:

 show: '=slidesToShow',
 scroll: '=slidesToScroll',

From parent controller i get "calculateGamesCount" , but after window resize carousel directive attrs dont change, its stay the same.

$scope.calculateGamesCount = Math.floor(( window.innerWidth - 90 ) / 232 );

// Get value after resize
angular.element($window).bind('resize',function(){
    $scope.$apply(function(){
        $scope.calculateGamesCount = Math.floor(( window.innerWidth - 90 ) / 232 ) ;
    });
});

How i can fix it ?


Solution

  • Well there's workaround for your condition. You can have following generic directive which watches change in window size. Then you can watch the windowWidth variable in your controller which set every time there's change in window width inside directive. Inside watch function you first delete the ui-carousel component on your view by using ng-if then assign newly calculated value of calculateGamesCount & then make ng-if to true. By doing this your directive will be re-rendered every time there's change in window width.

    app.directive('resize', function ($window) {
        return function (scope, element) {
            var w = angular.element($window);
            scope.getWindowDimensions = function () {
                return {
                    'h': w.height(),
                    'w': w.width()
                };
            };
            scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {
                scope.windowHeight = newValue.h;
                scope.windowWidth = newValue.w;
    
            }, true);
    
            w.bind('resize', function () {
                scope.$apply();
            });
        }
    });
    

    Inside controller add this code:

    $scope.$watch('windowWidth', function(n, o){
            $scope.showCarousel = false;
            $timeout(function(){
                $scope.calculateGamesCount = Math.floor(( window.innerWidth - 90 ) / 232 );
                $scope.toShow = angular.copy($scope.calculateGamesCount);
                console.log($scope.calculateGamesCount);
                $scope.showCarousel = true;
            });
    });
    

    You can have resize directive on any parent element of ui-carousel tag directive. Working plunker example: https://plnkr.co/edit/ebi2b2z9o1IlbIMBcu8r?p=preview