Home  >  Article  >  Web Front-end  >  使用AngularJS实现可伸缩的页面切换的方法_AngularJS

使用AngularJS实现可伸缩的页面切换的方法_AngularJS

WBOY
WBOYOriginal
2016-05-16 15:53:411082browse

AngularJS 1.2 通过引入基于纯CSS class的切换和动画,在一个单页面应用创建页面到页面的切换变得更加的容易。只需要使用一个ng-view,让我们来看一下,一个引入众多的不同切换的可伸缩方法,以及指定的每个页面如何切入和切出。

演示: http://embed.plnkr.co/PqhvmW/preview

首先,标记:
 

 <div class="page-container">
  <div ng-view class="page-view" ng-class="pageAnimationClass"> </div>
 </div>

既然ng-view使用进入/离开动画,那么就能简单地在DOM里使用两个 ng-view 元素来进行新视图切入和旧视图切出。因此,我们在使用相对定位的 page-container 元素里,使用绝对定位建立了ng-view,从而支持任意一种定位切换。

'go' 方法

在单页面应用里,我们仍想启用通过URL导航和确保浏览器的回退和下一步按钮如预期的功能。所以一旦我们在$routeProvider设好我们的路由,模板,控制器(可选的解析),我们可以在一个 ng-click 里使用一个相对路径来直接切换页面:
 

 <a ng-click="/page2">Go to page 2</a>

那样也可以工作,但是我们需要在ng-view 硬编码指定切换一个class 。以此代替,让我们在 $rootScope 上创建一个 'go' 方法,可以让我们指定一个路径和一个像这样的切换:
 

 <a ng-click="go('/page2', 'slideLeft')">Go to page 2</a>

这是我们 $rootScope 'go' 方法:
 

$rootScope.go = function (path, pageAnimationClass) {
 
  if (typeof(pageAnimationClass) === 'undefined') { // Use a default, your choice
    $rootScope.pageAnimationClass = 'crossFade';
  }
     
  else { // Use the specified animation
    $rootScope.pageAnimationClass = pageAnimationClass;
  }
 
  if (path === 'back') { // Allow a 'back' keyword to go to previous page
    $window.history.back();
  }
     
  else { // Go to the specified path
    $location.path(path);
  }
};

现在,任何你第二个参数指定的 切换类 将会添加到 ng-view 并且 go 方法将会用指定的第一个参数改变页面路径。

切换类

接下来要做的就是创建一个任意数量的切换类,并使用 ngAnimate module 提供的钩子,例如:
 

/* slideLeft */
.slideLeft {
  transition-timing-function: ease;
  transition-duration: 250ms;
}
 
.slideLeft.ng-enter {
  transition-property: none;
  transform: translate3d(100%,0,0);
}
 
.slideLeft.ng-enter.ng-enter-active {
  transition-property: all;
  transform: translate3d(0,0,0);
}
 
.slideLeft.ng-leave {
  transition-property: all;
  transform: translate3d(0,0,0);
}
 
.slideLeft.ng-leave.ng-leave-active {
  transition-property: all;
  transform: translate3d(-100%,0,0);
}


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn