Angularjs中UI Router的使用方法

字號:


    學(xué)習(xí)使用angular中,ui-route是其中的一個(gè)難點(diǎn),簡單使用沒什么問題,但涉及到多級嵌套,就感覺有茫然,查了很多資料,踩過很多坑,到目前為止也不能說對ui-route有全面了解;這里只是把填補(bǔ)的幾個(gè)坑記錄一下備忘:
    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 表明此狀態(tài)不能被顯性激活,只能被子狀態(tài)隱性激活。不能顯性激活即不能直接通過"/shop"訪問此狀態(tài)路由,那不就是一條死路嗎?那要你何用。等等,我們再看看后面一句:能被子狀態(tài)隱性激活,貌似還能活起來,怎么讓他活起來?我們再看下面的代碼:
    .state('shop.main',{
       url:"/:id",
       abstract: true,
        templateUrl:"templates/shop/main2.html",
        controller:"ShopMainController" 
     })
    狀態(tài):"shop.main"是shop的子狀態(tài),按理論shop.main可以激活shop,我們只需要這樣去訪問:/shop/1,這樣我們可以激活shop狀態(tài),和"shop.main"
    我們暫且不著急,我再再給加上abstract屬性,玩點(diǎn)刺激的,我們再把激活點(diǎn)再往后一級看下面代碼:
    .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>"
    })
    我看狀態(tài)"shop.main.info"這個(gè)狀態(tài) 的url為""所以我們要激活這個(gè)狀態(tài)只需要這樣去訪問"shop/1"所有可以做為"shop.main"的一個(gè)默認(rèn)子狀態(tài)。
    此時(shí)模塊的嵌套關(guān)系為:list.html嵌套main.html,main.html嵌套info.html。我們可以通過"shop/:id"的url激活這個(gè)三層嵌套。
    2.控制器中參數(shù)的使用:
    這個(gè)沒什么難點(diǎn),在控制器中注入"$stateParams" url參數(shù)在這個(gè)對象里可以拿得到 :
    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.怎么防止模板緩存
    在開發(fā)過程中,模板緩存嚴(yán)重影響我們調(diào)試,有時(shí)候代碼修改了,模板卻沒有任何變化。很苦惱,其他我們只需要監(jiān)聽下stateChangeSuccess,然后再清除$templateCache就行,這里我們采用run方法添加監(jiān)聽:
    bookApp.run(['$rootScope','$templateCache', function ($rootScope, $templateCache) { 
     var stateChangeSuccess = $rootScope.$on('$stateChangeSuccess', stateChangeSuccess); 
     function stateChangeSuccess($rootScope) { 
      $templateCache.removeAll();  
     } 
    }]);
    以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助。