Angularjs改变了窗口大小的视图

Angularjs change views on window resize

本文关键字:视图 窗口大小 改变 Angularjs      更新时间:2023-09-26

我忙于Angularjs应用程序,一切都很好,但是我在实现网站的移动版本方面有问题。我不能只做响应式样式,我需要为移动/桌面版本使用不同的视图文件。所以,在我的应用程序中,我使用ui-router配置如下:

dopGruz
    .config([ '$stateProvider', '$urlRouterProvider','$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider){
    $stateProvider
        .state('root',{
            views: {
                "navbar" : {
                    controller: 'viewsController',
                    templateProvider: function($http, viewsWatcherFactory) {
                        return viewsWatcherFactory
                            .get('app/views/nav-bar.html')
                            .then(function(obj){
                                return $http
                                    .get(obj.templateName)
                                    .then(function(tpl){
                                        return tpl.data;
                                    });
                            });
                } },
                "" : { template: '<div ui-view></div>' }
            }
        })

我的工厂返回基于窗口宽度的移动模板

dopGruz.factory('viewsWatcherFactory', [
    '$http',
    '$timeout',
    function($http, $timeout) {
        var _ifMobile = (function(){
            return window.innerWidth < 850;
        })();
        return {
            get : function(id) {
                return $timeout(function(){
                    var path = id;
                    if (_ifMobile) {
                        path = id.split('/');
                        path.splice(path.length-1,0,'mobile');
                    }
                    if (Array.isArray(path)) {
                        path = path.join('/');
                    }
                    return {templateName : path};
                }, 0);
            }
        };
    }
]);

这在页面加载时效果很好-如果窗口宽度<850px -它实际上加载模板的移动版本。但是是否有一种方法可以基于事件手动调用templateProvider ?我有一个控制器,我想在其中实现它:

dopGruz.controller('viewsController', function ($scope,$window) {
    angular.element($window).bind('resize', function() {
        console.log($window.innerWidth);
        // do some magic and call templateProvider and update views files.
        $scope.$digest();
    });
});

也许有更简单和正确的方法来做这件事。如有任何帮助,不胜感激

我将使用ng-include并将src属性设置为指向模板的移动版或桌面版的作用域变量。我没有从头到尾讲完,但是你应该从这个例子中得到一些想法。

控制器:

app.controller('MainCtrl', function($scope) {
$scope.templates =
[ { name: 'mobile.html', url: 'mobile.html'},
  { name: 'desktop.html', url: 'desktop.html'} ];
$scope.template = $scope.templates[0];
});
主模板:

<body ng-controller="MainCtrl">
   <ng-include class="col-md-12" src="template.url"></ng-include>
</body>
移动模板:

<div>mobile template</div>
桌面模板:

<div>desktop template</div>