1. 程式人生 > >angularJs模組ui-router之狀態管理

angularJs模組ui-router之狀態管理

ui-router 的工作原理非常類似於 Angular 的路由控制器,但它只關注狀態。

  • 在應用程式的整個使用者介面和導航中,一個狀態對應於一個頁面位置
  • 通過定義controllertemplateview等屬性,來定義指定位置的使用者介面和介面行為
  • 通過巢狀的方式來解決頁面中的一些重複出現的部位

最簡單的形式

模板可以通過下面這種最簡單的方式來指定

<!-- in index.html -->
<body ng-controller="MainCtrl">
    <section ui-view></section>
</body>
// in app-states.js (or whatever you want to name it)
$stateProvider.state('contacts', {
  template: '<h1>My Contacts</h1>'
})


模板將被插入哪裡?


啟用狀態
狀態被啟用時,它的模板會自動插入到父狀態對應的模板中包含ui-view屬性的元素內部。如果是頂層的狀態,那麼它的父模板就是index.html

有三種方法來啟用狀態:

  1. 呼叫$state.go()方法,這是一個高階的便利方法;
  2. 點選包含ui-sref指令的連結;
  3. 導航到與狀態相關聯的 url。

Templates 模板

可以通過下面幾種方法來配置一個狀態的模板。

方法一:配置template屬性,指定一段 HTML 字串,這人是設定模板的最簡單的方式

$stateProvider.state('contacts', {
  template: '<h1>My Contacts</h1>'
})

方法二:配置templateUrl屬性,來載入指定位置的模板,這是設定模板的常用方法。

$stateProvider.state('contacts', {
  templateUrl: 'contacts.html'
})

templateUrl的值也可以是一個函式返回的url,函式帶一個預設引數stateParams

複製程式碼
$stateProvider.state('contacts', {
  templateUrl: function (stateParams){
    return '/partials/contacts.' + stateParams.filterBy + '.html';
  }
})
複製程式碼

方法三:通過templateProvider函式返回模板的 HTML。templateUrl的值也可以是一個函式返回的url,函式帶一個預設引數stateParams

複製程式碼
$stateProvider.state('contacts', {
  templateProvider: function ($timeout, $stateParams) {
    return $timeout(function () {
      return '<h1>' + $stateParams.contactId + '</h1>'
    }, 100);
  }
})
複製程式碼

如果想在狀態被啟用前,讓<ui-view>有一些預設的內容,當狀態被啟用之後預設內容將被狀態對應的模板替換。

複製程式碼
<body>
    <ui-view>
        <i>Some content will load here!</i>
    </ui-view>
</body>
複製程式碼

Controllers 控制器

可以為模板指定一個控制器(controller)。警告:控制器不會被例項化如果模板沒有定義。

設定控制器:

複製程式碼
$stateProvider.state('contacts', {
  template: '<h1>{{title}}</h1>',
  controller: function($scope){
    $scope.title = 'My Contacts';
  }
})
複製程式碼

如果在模組中已經定義了一個控制器,只需要指定控制器的名稱即可:

$stateProvider.state('contacts', {
  template: ...,
  controller: 'ContactsCtrl'
})

使用controllerAs語法:

$stateProvider.state('contacts', {
  template: ...,
  controller: 'ContactsCtrl as contact'
})

對於更高階的需要,可以使用controllerProvider來動態返回一個控制器函式或字串:

複製程式碼
$stateProvider.state('contacts', {
template: ...,
controllerProvider: function($stateParams) {
var ctrlName = $stateParams.type + "Controller";
return ctrlName;
}
})
複製程式碼

控制器可以使用$scope.on()方法來監聽事件狀態轉換。

控制器可以根據需要例項化,當相應的scope被建立時。例如,當用戶點選一個url手動導航一個狀態時,$stateProvider將載入對應的模板到檢視中,並且將控制器和模板的scope繫結在一起。

解決器 Resolve

可以使用resolve為控制器提供可選的依賴注入項。

resolve配置項是一個由key/value構成的物件。

  • key – {string}:注入控制器的依賴項名稱。
  • factory - {string|function}:
    • string:一個服務的別名
    • function:函式的返回值將作為依賴注入項,如果函式是一個耗時的操作,那麼控制器必須等待該函式執行完成(be resolved)才會被例項化。

例子

controller例項化之前,resolve中的每一個物件都必須 be resolved,請注意每個 resolved object 是怎樣作為引數注入到控制器中的。

複製程式碼
$stateProvider.state('myState', {
      resolve:{

         // Example using function with simple return value.
         // Since it's not a promise, it resolves immediately.
         simpleObj:  function(){
            return {value: 'simple!'};
         },

         // Example using function with returned promise.
         // 這是一種典型使用方式
         // 請給函式注入任何想要的服務依賴,例如 $http
         promiseObj:  function($http){
            // $http returns a promise for the url data
            return $http({method: 'GET', url: '/someUrl'});
         },

         // Another promise example. 
         // 如果想對返回結果進行處理, 可以使用 .then 方法
         // 這是另一種典型使用方式
         promiseObj2:  function($http){
            return $http({method: 'GET', url: '/someUrl'})
               .then (function (data) {
                   return doSomeStuffFirst(data);
               });
         },        

         // 使用服務名的例子,這將在模組中查詢名稱為 'translations' 的服務,並返回該服務 
         // Note: The service could return a promise and
         // it would work just like the example above
         translations: "translations",

         // 將服務模組作為解決函式的依賴項,通過引數傳入
         // 提示:依賴項 $stateParams 代表 url 中的引數
         translations2: function(translations, $stateParams){
             // Assume that getLang is a service method
             // that uses $http to fetch some translations.
             // Also assume our url was "/:lang/home".
             translations.getLang($stateParams.lang);
         },

         // Example showing returning of custom made promise
         greeting: function($q, $timeout){
             var deferred = $q.defer();
             $timeout(function() {
                 deferred.resolve('Hello!');
             }, 1000);
             return deferred.promise;
         }
      },

      // 控制器將等待上面的解決項都被解決後才被例項化
      controller: function($scope, simpleObj, promiseObj, promiseObj2, translations, translations2, greeting){
          
          $scope.simple = simpleObj.value;

          // 這裡可以放心使用 promiseObj 中的物件
          $scope.items = promiseObj.items;
          $scope.items = promiseObj2.items;

          $scope.title = translations.getLang("english").title;
          $scope.title = translations2.title;

          $scope.greeting = greeting;
      }
   })
複製程式碼

為 $state 物件提供自定義資料

可以給 $state 物件提供自定義資料(建議使用data屬性,以免衝突)

複製程式碼
// 基於物件和基於字串定義 state 的例子
var contacts = { 
    name: 'contacts',
    templateUrl: 'contacts.html',
    data: {
        customData1: 5,
        customData2: "blue"
    }  
}
$stateProvider
  .state(contacts)
  .state('contacts.list', {
    templateUrl: 'contacts.list.html',
    data: {
        customData1: 44,
        customData2: "red"
    } 
  })
複製程式碼

可以通過下面的方式來訪問上面定義的資料:

function Ctrl($state){
    console.log($state.current.data.customData1) // 輸出 5;
    console.log($state.current.data.customData2) // 輸出 "blue";
}

onEnter 和 onExit 回撥函式

onEnteronExit回撥函式是可選配置項,分別稱為當一個狀態變得活躍的和不活躍的時候觸發。回撥函式也可以訪問所有解決依賴項。

複製程式碼
$stateProvider.state("contacts", {
  template: '<h1>{{title}}</h1>',
  resolve: { title: 'My Contacts' },
  controller: function($scope, title){
    $scope.title = 'My Contacts';
  },
  // title 是解決依賴項,這裡也是可以使用解決依賴項的
  onEnter: function(title){ 
    if(title){ ... do something ... }
  },
  // title 是解決依賴項,這裡也是可以使用解決依賴項的
  onExit: function(title){
    if(title){ ... do something ... }
  }
})
複製程式碼

State Change Events 狀態改變事件

所有這些事件都是在$rootScope作用域觸發

  • $stateChangeStart - 當模板開始解析之前觸發
$rootScope.$on('$stateChangeStart', 
function(event, toState, toParams, fromState, fromParams){ ... })

注意:使用event.preventDefault()可以阻止模板解析的發生

複製程式碼
$rootScope.$on('$stateChangeStart', 
function(event, toState, toParams, fromState, fromParams){ 
    event.preventDefault(); 
    // transitionTo() promise will be rejected with 
    // a 'transition prevented' error
})
複製程式碼
  • $stateNotFound - v0.3.0 - 在 transition 時通過狀態名查詢狀態,當狀態無法找到時發生。該事件在 scope 鏈上廣播,只允許一次處理錯誤的機會。unfoundState將作為引數傳入事件監聽函式,下面例子中可以看到unfoundState的三個屬性。使用 event.preventDefault() 來阻止模板解析,
複製程式碼
// somewhere, assume lazy.state has not been defined
$state.go("lazy.state", {a:1, b:2}, {inherit:false});

// somewhere else
$scope.$on('$stateNotFound', 
function(event, unfoundState, fromState, fromParams){ 
    console.log(unfoundState.to); // "lazy.state"
    console.log(unfoundState.toParams); // {a:1, b:2}
    console.log(unfoundState.options); // {inherit:false} + default options
})
複製程式碼
  • $stateChangeSuccess - 當模板解析完成後觸發
$rootScope.$on('$stateChangeSuccess', 
function(event, toState, toParams, fromState, fromParams){ ... })
  • $stateChangeError - 當模板解析過程中發生錯誤時觸發
$rootScope.$on('$stateChangeError', 
function(event, toState, toParams, fromState, fromParams, error){ ... })

View Load Events 檢視載入事件

$viewContentLoading - 當檢視開始載入,DOM渲染完成之前觸發,該事件將在$scope鏈上廣播此事件。

複製程式碼
$scope.$on('$viewContentLoading', 
function(event, viewConfig){ 
    // Access to all the view config properties.
    // and one special property 'targetView'
    // viewConfig.targetView 
});
複製程式碼
  • $viewContentLoaded - 當檢視載入完成,DOM渲染完成之後觸發,檢視所在的$scope發出該事件。
$scope.$on('$viewContentLoading', 
$scope.$on('$viewContentLoaded', 
function(event){ ... });