当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > Angularjs中UI Router的使用方法

Angularjs中UI Router的使用方法

2018年06月17日  | 移动技术网IT编程  | 我要评论

学习使用angular中,ui-route是其中的一个难点,简单使用没什么问题,但涉及到多级嵌套,就感觉有茫然,查了很多资料,踩过很多坑,到目前为止也不能说对ui-route有全面了解;这里只是把填补的几个坑记录一下备忘:

1.abstract的使用:

$stateprovider
  .state('shop',{
    resolve:{
      "shoplist":function($http){
        return $http({
          url:"/bookapp/data/shoplist.php",
          method:"get"
        })
      }
    },
    abstract: true,
    url:"/shop",
    templateurl:"templates/shop/list.html",
    controller:"shoplistcontroller"
})

使用abstract属性有什么用,官方说明:abstract: true 表明此状态不能被显性激活,只能被子状态隐性激活。不能显性激活即不能直接通过"/shop"访问此状态路由,那不就是一条死路吗?那要你何用。等等,我们再看看后面一句:能被子状态隐性激活,貌似还能活起来,怎么让他活起来?我们再看下面的代码:

 .state('shop.main',{
    url:"/:id",
    abstract: true,
     templateurl:"templates/shop/main2.html",
     controller:"shopmaincontroller"  
  })

状态:"shop.main"是shop的子状态,按理论shop.main可以激活shop,我们只需要这样去访问:/shop/1,这样我们可以激活shop状态,和"shop.main"

我们暂且不着急,我再再给加上abstract属性,玩点刺激的,我们再把激活点再往后一级看下面代码:

  .state('shop.main.info',{
    url:"",
    templateurl:"templates/shop/info.html",
    cache:'false',
    controller:"infocontroller"
  })
  .state('shop.main.author',{
    url:"/author",
    template:"<div>authorauthorauthorauthorauthor</div>"
  })
  .state('shop.main.samebook',{
    url:"samebook",
    template:"<div>samebooksamebooksamebooksamebooksamebooksamebook</div>"
  })

我看状态"shop.main.info"这个状态 的url为""所以我们要激活这个状态只需要这样去访问"shop/1"所有可以做为"shop.main"的一个默认子状态。

此时模块的嵌套关系为:list.html嵌套main.html,main.html嵌套info.html。我们可以通过"shop/:id"的url激活这个三层嵌套。

2控制器中参数的使用:

这个没什么难点,在控制器中注入"$stateparams" url参数在这个对象里可以拿得到 :

shop.controller("shopmaincontroller",['$scope','$stateparams','$rootscope',function($scope,$stateparams,$rootscope){
  $scope.persons = [1,2,3,4,5,6];
  $scope.good = {
    id:$stateparams.id
  }
  cfploadingbar.start();

}]);

3.怎么防止模板缓存

在开发过程中,模板缓存严重影响我们调试,有时候代码修改了,模板却没有任何变化。很苦恼,其他我们只需要监听下statechangesuccess,然后再清除$templatecache就行,这里我们采用run方法添加监听:

bookapp.run(['$rootscope','$templatecache', function ($rootscope, $templatecache) { 

 var statechangesuccess = $rootscope.$on('$statechangesuccess', statechangesuccess); 

 function statechangesuccess($rootscope) { 
  $templatecache.removeall();  
 } 
}]);

以上就是本文的全部内容,希望对大家的学习有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网