AngularJS UIRouter - 在后退单击时删除正文样式

时间:2016-06-24 21:57:28

标签: angularjs jasny-bootstrap

问题背景:

我有一个Angular应用程序有2个视图,使用UIRouter我在视图中交换URL也被路由

在我的观点中,我使用Jasny Bootstrap来制作画布菜单' push'菜单,如图所示:

https://codepen.io/rugor/pen/eiyzh

当菜单显示如下所示时,这会为body标签添加样式:

<body translate="no" class="canvas-slid" style="position: relative; left: 300px; overflow: hidden; right: -300px;">
     // Other HTML
</body>

问题:

我有以下Index.html视图,用作我要注入的每个应用页面的主要ui-view容器:

<body ng-app="app">
    <div ui-view>
       //Views injected here when routed.
    </div>
</body

如果我浏览我的主页,即Home.cshtml,我会收到以下页面:

enter image description here

主页的正文风格:

<body ng-app="app" class="ng-scope">
   //Homepage Html

然后我浏览到Update.html页面并显示Jansy Off Canvas菜单:

enter image description here

请注意,Index.cshtml页面的body标签已添加以下样式以显示非画布菜单:

<body ng-app="app" class="ng-scope canvas-slid" style="position: relative; left: 300px; overflow: hidden; padding-right: 17px; right: -300px;">
</body>

这是问题的开始。

如果我现在点击浏览器上的 后退按钮 ,并使用Jansy off canvas菜单 显示 ,那么正文样式从body标签中删除 ,如下所示:

enter image description here

仍然应用了身体风格:

<body ng-app="app" class="ng-scope canvas-slid" style="position: relative; left: 300px; overflow: hidden; padding-right: 17px; right: -300px;">
</body>

我该如何克服这个问题?当用户点击浏览器上的后退按钮时,我可以删除ui-view Index.html中body标签上的任何样式吗?如果是这样的话?

我理解为什么会发生这种情况,如果用户要关闭画布菜单并点击回来,则不会发生问题。

由于在视图之间共享主体,我需要一种在后退点击时清除样式的方法,以有效地将其重置为空。

3 个答案:

答案 0 :(得分:4)

您可以为$ rootScope添加侦听器以进行locationchangestart或locationchangesucess事件(https://docs.angularjs.org/api/ng/service/ $ location)或statechangestart / statechangesuccess https://github.com/angular-ui/ui-router/wiki)并从正文中删除类。

为了更加花哨,你可以在body元素上实现它作为指令:

<body mydirective>

    app.directive(mydirective,
 ...
    link : function(scope, element, attrs) {
        scope.$on('$stateChangeStart', function () {
            element.removeClass("canvas-slid");
        }
    }

答案 1 :(得分:1)

实际上,这是jasny-bootstrap插件的一个小问题,在这里我给出了一个临时解决方案来删除样式。

var _enableScrolling = $.fn.offcanvas.Constructor.prototype.enableScrolling;
$.fn.offcanvas.Constructor.prototype.enableScrolling = function () {
 _enableScrolling.apply(this, arguments);
 $('body').css({
        'overflow': '',
        'padding-right': '' 
    });
 } 

但是您可以使用jasny-bootstrap的master分支查看实际修复

jasny-bootstrap ui stlye remove

答案 2 :(得分:1)

按下后退按钮时,可以尝试使用jquery删除内联CSS。 因此,当您按下后退按钮时,无论控制器加载什么,请尝试将此代码添加到其中。

$('body').removeAttr("style")

它将删除应用于body标签的任何内联样式

相关问题