我是AngularJS的新手,想要实现路由依赖的页面转换.例如,我希望页面向左滑动,向右滑动或根据路线向下滑动.
下面我的’Plunker’通过监听$routeChangeSuccess事件然后将一个特定于转换风格的CSS类应用于进入和离开视图(灵感来自http://phillippuleo.com/articles/scalable-approach-page-transitions-angularjs)来实现这一点:
http://plnkr.co/edit/ee4CHfb8kZC1WxtDM9wr?p=preview
但是,在事件监听器中调用$scope.$apply()会使AngularJS发出错误消息’$digest has progress in’.但是如果我不调用$scope.$apply()则不会更新离开视图的CSS类,并且动画无法正常工作.
这里发生了什么?
我看着你的傻瓜.问题在于您使用类为视图设置动画的方式.
当触发$routeChangeSuccess事件时,ngView已经删除了该类,然后才有机会改变方向.你可以通过快速应用新类来覆盖它,这样就不会注意到它,但是你会得到正在进行的摘要错误.
我提出了一个指令:
app.directive('animClass',function($route){ return { link: function(scope,elm,attrs){ var enterClass = $route.current.animate; elm.addClass(enterClass); scope.$on('$destroy',function(){ elm.removeClass(enterClass); elm.addClass($route.current.animate); }) } } });
为每个路由声明一个animate选项:
app.config(function($routeProvider) { $routeProvider. when("/page1",{ templateUrl: "page1.html",controller: "Page1Ctrl",animate: "slideLeft" }). when("/page2",{ templateUrl: "page2.html",controller: "Page2Ctrl",animate: "slideRight" }). otherwise({ redirectTo: "/page1" }); });
并将其添加到ngView,如下所示:
<div ng-view ng-controller="ViewCtrl" anim-class class="view"></div>
CSS:
.view { width: 100%; padding-left: 1em; position:absolute; top: 0; left: 0; } .slideLeft.ng-enter,.slideLeft.ng-leave,.slideRight.ng-enter,.slideRight.ng-leave { -webkit-transition:all 1s; transition:all 1s; } .slideLeft.ng-enter { left:100%; } .slideLeft.ng-enter.ng-enter-active { left:0; } .slideLeft.ng-leave.ng-leave-active { left:-100%; } .slideRight.ng-enter { left:-100%; } .slideRight.ng-enter.ng-enter-active { left:0; } .slideRight.ng-leave.ng-leave-active { left:100%; }