Scottie
Scottie

Reputation: 11308

How can I force a re-load of a template in AngularJS on resize?

I'm fairly new to AngularJS and I'm sure there is a simple explaination for this problem...

I am attempting to load a different template file depending on the size of the screen in AngularJS.

The initial load seems to work fine, however, if I resize the screen, it's not changing the template.

Here's a plunker that shows the issue. (Note you have to drag the splitter to resize the window).

http://plnkr.co/edit/MneEKO9Q3hAGHvsRuQWw?p=preview

Html:

<!DOCTYPE html>
<html>

  <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
    <script src="script.js"></script>

  </head>

  <body ng-app="testApp">
    <ng-datalist></ng-datalist>

  </body>

</html>

JS:

angular.module('testApp', []).directive('ngDatalist', ['$compile', '$window', function ($compile, $window) {
    return {
        restrict: 'E',
        link: function (scope, element, attrs) {
            scope.xsTemplateUrl = "datalist-xs.html";
            scope.xlTemplateUrl = "datalist-xl.html";

            var win = angular.element($window);
            var size = win.width();
            console.log(size);
            if (size <= 800) {
                scope.templateUrl = scope.xsTemplateUrl;
                scope.currentSize = "XS";
            }
            else {
                scope.templateUrl = scope.xlTemplateUrl;
                scope.currentSize = "XL";
            }

            win.bind("resize", function (e) {
                var size = win.width();
                console.log(size);
                if ((size <= 800) && (scope.currentSize !== "XS")) {
                    scope.templateUrl = scope.xsTemplateUrl;
                    scope.currentSize = "XS";
                    console.log(scope.templateUrl);
                }
                else if ((size > 800) && (scope.currentSize !== "XL")) {
                    scope.templateUrl = scope.xlTemplateUrl;
                    scope.currentSize = "XL";
                    console.log(scope.templateUrl);
                }
            });

            scope.name = "John Wayne";
            var el = angular.element("<div ng-include='templateUrl'></div>");
            $compile(el)(scope);
            element.replaceWith(el);
        }
    };
}]);

Upvotes: 0

Views: 758

Answers (1)

cage rattler
cage rattler

Reputation: 1597

Just add

scope.$apply();

at the end of your window resize handler.

Upvotes: 4

Related Questions