AngularJS-ui根据窗口宽度切换手风琴

时间:2014-01-20 04:46:43

标签: angularjs angular-ui

我希望在浏览器处于一定宽度时以编程方式添加accordion functionality。当$window手表报告宽度低于400px时,我想我可能只会消灭手风琴,而不是时再次重新启动手风琴。但在搜索了几个小时之后,这似乎是一个愚蠢的想法。有没有办法做到这一点或更好的方式来存档相同的结果?

1 个答案:

答案 0 :(得分:1)

好的,对于可能面临类似问题的每个人来说,这就是我们最终做的事情:

在Angular配置中,我们添加了一个动态路由器:

$routeProvider
.when('/:a', {
    template: '<div data-ng-include="templateUrl">Loading...</div>',
    controller: 'DynamicController'
})

然后控制器看起来像这样:

.controller('DynamicController', function ($scope, $rootScope, $routeParams) {
var mobile = false; //set desktop first as mobil has more logic
    var maxWidth = 768; //adjust this value in media queries aswell!
    var _isMobile = "";
    //listen for changes on the scope var windowWidth
    $rootScope.$watch('windowWidth',function(){
        //check that we have not exceeded our max width
        if($rootScope.windowWidth < maxWidth) {
            _isMobile = "mobile"; //set the current view based on the width to mobile
        }
        else {
            _isMobile = "desktop"; //set the current view based on the width to desktop
        }
        $scope.templateUrl = function() {
            var temp = (_isMobile ? _isMobile : 'desktop');
            return 'views/' + temp + '.html';
        }(); //immediate gets called every time the windowWidth var changes passes in the current required view as a string.
    });
})

为此指令设置了一个手表:

angular.module('app.config',[])
.directive('resize', function ($window) {
    return {
        controller: function ($scope, $rootScope) {
            $rootScope.windowWidth = $window.innerWidth;
            angular.element($window).bind('resize', function () {
                $rootScope.$apply(function () {
                    $rootScope.windowWidth = $window.innerWidth;
                });
            });

        }
    };
});

现在我们有两个移动和桌面视图,它们都使用相同的内容绘制,但将它们包装成手风琴或其他容器。

这似乎很有效,希望能帮助其他网民。