angularJs ui-router路由之多视图实现菜单缓存切换

896 阅读2分钟

**

angularJs ui-router路由之多视图实现菜单多页签

** 一个模板中存在多个ui-view,每个ui-view都存在唯一的名称作为标识,通过v-show来判断当前的ui-view是否显示,实现如下图效果 angularJs实现菜单的tab切换 很多文章都有讲到ui-router之多视图(参考文章:bubkoo.com/2014/01/01/…

//currentTabs就是当前已打开的全部菜单,a标签一定不能加ui-self,否则就无法缓存页面,相当于再次请求加载当前路由模块
<ul>
<li ng-repeat="item in currentTabs" ng-class="{'active':item.active}">
	<a ng-click="show(item,currentTabs);" >{{item.label}}
		<i  ng-click="closeMenuTabs(item)" alt="关闭" class="fa fa-times close-gray"></i>
	</a>
</li>
</ul>
//ui-view的值为路由状态管理器中的views,不懂的请参考(参考文章:http://bubkoo.com/2014/01/01/angular/ui-router/guide/multiple-named-views/)
根据控制ng-show来判断当前模块是否显示
<div style="width: 100%; height: 100%" class="app-content-body fade-in-up"  ng-repeat="item in currentTabs" id={{item.name}} ui-view={{item.name}} ng-show="item.active">
 </div>
//通过点击a标签,改变ui-view
	$scope.show = function(current,alltabs){
		jQuery.each($rootScope.currentTabs,function(){
			if(current.data.href == this.data.href){
				this.active = true;
			}else{
				this.active = false;
			}
		});
		$scope.openMenu(currentUrl);
	}

    $scope.openMenu = function(url,type){
		  if(url!=null && url!='null' && url!=''){
			  if(type==3){//新窗口打开
				  if(url.indexOf("http")==-1){
					  url = "http://"+url;
				  }
				  window.open(url);
			  }else if(type==2){//本窗口打开
				  if(url.indexOf("http")==-1){
					  url = "http://"+url;
				  }
				  window.location.href = url;; 
			  }else{//本工作区打开
				  if(url.indexOf("#")==0){
					  $rootScope.otherUrl = false;
					  window.location = url; 
				  }else{
					  $rootScope.otherUrl = true;
					  window.open(url);
					  return;
					  //$state.go('app.showOutSide', {urlstr: url});
				  }
			  }
		  }
	};

以上可以实现基本的菜单切换,但是需要注意的是:

1.每个页面模块的controller的命名不能相同,否则会出现调用方法的混乱,可能会进入到另一个同名的controller中调用方法;

2.当使用此方法对页面进行缓存,如果打开多个模块用到websocket接受服务器消息时,不能使用WebSocket.onmessage监听和接受服务器消息,否则可能会调用其他controller中WebSocket.onmessage,当前的页面模块就会监听不到服务器消息,这时我们可以使用 socket.addEventListener('message', function (event) { console.log('Message from server ', event.data); }); 进行服务器消息的监听,并在方法体内做判断,是否是当前页面需要的。

3.如果某个页面的弹出框用到了路由调用则弹框中的页面不会显示,所以建议不要在弹框中直接调用路由加载页面,或者可以在index.jsp中:


<div class="app" id="app"  ng-class="{'app-header-fixed':app.settings.headerFixed,'app-header-fixed-tabs':app.settings.tabsFixed, 'app-aside-fixed':app.settings.asideFixed, 'app-aside-folded':app.settings.asideFolded, 'app-aside-dock':app.settings.asideDock, 'container':app.settings.container}" ui-view>
	<div ui-view></div>
</div>

4.如果几个模块views里面的name一样,则会出现加载的页面重复的问题;

5.style样式:如果多个模块存在相同名称的选择器,则样式会冲突; 还有些问题会在后面慢慢补充。

6.页面打开太多会出现卡顿现象

7.一定要引入<script src="vendor/angular/angular-ui-router-ext/ct-ui-router-extras.min.js"></script>,否则会出现ui-view没有缓存的情况