1. 程式人生 > >1、Angular-Ui Router 狀態概要

1、Angular-Ui Router 狀態概要


狀態管理器.

新的狀態管理器($stateProvider) 類似於Angular's v1 的路由工作方式, 但更完美.

  • A state corresponds to a "place" in the application in terms of the overall UI and navigation. 
    在整個UI和導航方面,一個狀態對應於應用程式中的“位置”。
  • A state (via the controller / template / view properties) describes what the UI looks like and does at that place.
    一個狀態(通過controller / template / view屬性)描述UI在那個地方是什麼樣子的。
  • States often have things in common, and the primary way of factoring out these commonalities in this model is via the state hierarchy, i.e. parent/child states aka nested states.
    狀態通常有一些共同點,在這個模型中分解這些共性的主要方法是通過狀態層次結構,即父/子狀態,即巢狀狀態。

The simplest form of state
最簡單的狀態形式

A state in its simplest form can be added like this (typically within module.config

):

最簡單形式的狀態可以像這樣新增(一般在module.config中新增):
<!-- 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>'
})

Where does the template get inserted?
模板在哪裡插入?

When a state is activated, its templates are automatically inserted into the ui-view of its parent state's template. If it's a top-level state—which 'contacts' is because it has no parent state–then its parent template is index.html.

當一個狀態被啟用時,它的模板會自動被插入到它的父狀態模板的ui檢視中。如果是頂級狀態,即“聯絡人”是因為它沒有父狀態,那麼它的父模板是index.html。

Right now, the 'contacts' state won't ever be activated. So let's see how we can activate a state. 
現在,“聯絡人”狀態永遠不會被啟用。我們來看看如何啟用一個狀態。

Activating a state
啟用狀態

There are three main ways to activate a state:
啟用一個狀態有三種主要方式:

  1. Call $state.go(). High-level convenience method. Learn More 
    呼叫$state.go()方法,高階的使用方法。詳情
  2. Click a link containing the ui-sref directive. Learn More
    單擊包含ui-sref指令的標籤。詳情
  3. Navigate to the url associated with the state. Learn More
    導航到與狀態相關聯的url。詳情.

Templates
模板

There are several methods for configuring a state's template.
有幾種配置狀態模板的方法。

As seen above, the simplest way to set your template is via the template config property.
如上面所示,設定模板的最簡單方法是通過(template屬性)配置。

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

Instead of writing the template inline you can load a partial. (This is probably how you'll set templates most of the time.)
您可以通過URL載入一個模板,而不是內聯地編寫模板。(這是推薦的做法。)

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

templateUrl can also be a function that returns a url. It takes one preset parameter, stateParams, which is not injected.
templateUrl也可以是返回url的回撥函式。它需要一個預設的$stateParams引數,而不是注入的引數。

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

Or you can use a template provider function which can be injected, has access to locals, and must return template HTML, like this:
或者您可以使用一個模板提供者函式,它可以使用注入,可以訪問本地資料,但必須返回模板HTML,如下:

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

If you'd like your <ui-view> to have some default content before it's populated by a state activation, you can do that as well. The contents will be replaced as soon as a state is activated and populates the ui-view with a template.
如果您希望在它被一個狀態啟用之前有一些預設的內容,那麼您也可以這樣做。當一個狀態被啟用並使用一個模板填充ui-view時,內容將被替換。

<body>
    <ui-view>
        <i>Some content will load here!</i>
    </ui-view>
</body>

Controllers
控制器

You can assign a controller to your template. Warning: The controller will not be instantiated if template is not defined.
您可以將控制器分配給您的模板。警告:如果模板沒有定義,控制器將不會被例項化。

You set your controller like this:
您可以像這樣設定您的控制器:

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

Or if you already have a controller defined on the module, like this:
或者您已經像這樣定義了一個控制器

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

Alternatively using the "controller as" syntax the above becomes:
或者使用“controllerAs”語法,以上就變成了:

$stateProvider.state('contacts', {
  template: '<h1>{{contact.title}}</h1>',
  controller: function(){
    this.title = 'My Contacts';
  },
  controllerAs: 'contact'
})

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

Or for more advanced needs you can use the controllerProvider to dynamically return a controller function or string for you:
或者,對於更高階的需求,您可以使用controllerProvider來動態地返回控制器函式或字串:

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

Controllers can use the $scope.$on() method to listen for events fired by state transitions.
控制器可以使用$scope.$on()方法偵聽狀態轉換所觸發的事件。

Controllers are instantiated on an as-needed basis, when their corresponding scopes are created, i.e. when the user manually navigates to a state via a URL, $stateProvider will load the correct template into the view, then bind the controller to the template's scope.
控制器在需要的基礎上例項化,當它們對應的作用域被建立時,即當用戶通過URL手動導航到狀態時,$stateProvider將把正確的模板載入到檢視中,然後將控制器繫結到模板的作用域。

Resolve
延遲載入

You can use resolve to provide your controller with content or data that is custom to the state. resolve is an optional map of dependencies which should be injected into the controller.
您可以使用Resolve給您的狀態控制器提供自定義的內容或資料。Resolve是一個可選的依賴關係對映,它可被注入到控制器中。

If any of these dependencies are promises, they will be resolved and converted to a value beforethe controller is instantiated and the $stateChangeSuccess event is fired.
這些依賴項在控制器例項化之前,它們將被解析並轉換為一個值,並觸發$statechangesucess事件。

The resolve property is a map object. The map object contains key/value pairs of:
Resolve屬性是一個map物件。map物件包含鍵/值對:

  • key – {string}: a name of a dependency to be injected into the controller.
    key – {string}:要注入到控制器中的依賴項的名稱。
  • factory - {string|function}:
    • If string, then it is an alias for a service.
      如果是字串,則它是服務的名稱。
    • Otherwise if function, then it is injected and the return value is treated as the dependency. If the result is a promise, it is resolved before the controller is instantiated and its value is injected into the controller.
      否則,如果是一個函式,那麼它是一個依賴注入,返回值則是依賴注入項。如果結果是一個協議,那麼在控制器例項化之前,它就會被解析,並且它的值被注入到控制器中。

Examples:
示例

Each of the objects in resolve below must be resolved (via deferred.resolve() if they are a promise) before the controller is instantiated. Notice how each resolve object is injected as a parameter into the controller.
下面解析的每個物件會在控制器例項化之前解析完畢(via deferred.resolve() if they are a promise)。注意,如何將每個解析物件作為引數注入到控制器。

$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.
         // This is the typical use case of resolve.
         // You need to inject any services that you are
         // using, e.g. $http in this example
         promiseObj:  function($http){
            // $http returns a promise for the url data
            return $http({method: 'GET', url: '/someUrl'});
         },

         // Another promise example. If you need to do some 
         // processing of the result, use .then, and your 
         // promise is chained in for free. This is another
         // typical use case of resolve.
         promiseObj2:  function($http){
            return $http({method: 'GET', url: '/someUrl'})
               .then (function (data) {
                   return doSomeStuffFirst(data);
               });
         },        

         // Example using a service by name as string.
         // This would look for a 'translations' service
         // within the module and return it.
         // Note: The service could return a promise and
         // it would work just like the example above
         translations: "translations",

         // Example showing injection of service into
         // resolve function. Service then returns a
         // promise. Tip: Inject $stateParams to get
         // access to url parameters.
         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".
             return 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;
         }
      },

      // The controller waits for every one of the above items to be
      // completely resolved before instantiation. For example, the
      // controller will not instantiate until promiseObj's promise has 
      // been resolved. Then those objects are injected into the controller
      // and available for use.  
      controller: function($scope, simpleObj, promiseObj, promiseObj2, translations, translations2, greeting){
          $scope.simple = simpleObj.value;

          // You can be sure that promiseObj is ready to use!
          $scope.items = promiseObj.data.items;
          $scope.items = promiseObj2.items;

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

          $scope.greeting = greeting;
      }
   })

Learn more about how resolved dependencies are inherited down to child states.
瞭解更多關於如何將依賴關係繼承到子狀態的問題。

Attach Custom Data to State Objects
向狀態物件附加自定義資料

You can attach custom data to the state object (we recommend using a data property to avoid conflicts).
您可以將自定義資料附加到狀態物件(我們建議使用資料屬性來避免衝突)。

// Example shows an object-based state and a string-based 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"
    } 
  })

With the above example states you could access the data like this:
在上面的示例中,您可以這樣訪問資料:

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

Learn more about how custom data properties are inherited down to child states.
瞭解更多關於自定義資料屬性是如何繼承到子狀態的。

onEnter and onExit callbacks

There are also optional 'onEnter' and 'onExit' callbacks that get called when a state becomes active and inactive respectively. The callbacks also have access to all the resolved dependencies.
還有可選的“onEnter”和“onExit”回撥函式,當一個狀態變為活動狀態和不活動狀態時就會被呼叫。回撥也可以訪問所有已解析的依賴項。

$stateProvider.state("contacts", {
  template: '<h1>{{title}}</h1>',
  resolve: { 
     title: function () { 
       return 'My Contacts' 
     } 
  },
  controller: function($scope, title){
    $scope.title = title;
  },
  onEnter: function(title){
    if(title){ ... do something ... }
  },
  onExit: function(title){
    if(title){ ... do something ... }
  }
})

State Change Events
狀態變化事件

NOTE: State change events are deprecated, DISABLED and replaced by Transition Hooks as of version 1.0 (details
注意:狀態更改事件已被棄用,禁用並替換為版本1.0(詳細資訊))

All these events are fired at the $rootScope level.
所有這些事件都在$rootScope級別上被觸發。

  • $stateChangeStart - fired when the transition begins.在轉換開始時觸發。
$rootScope.$on('$stateChangeStart', 
function(event, toState, toParams, fromState, fromParams, options){ ... })

Note: Use event.preventDefault() to prevent the transition from happening.
注意:使用event.preventDefault()來防止轉換的發生。

$rootScope.$on('$stateChangeStart', 
function(event, toState, toParams, fromState, fromParams, options){ 
    event.preventDefault(); 
    // transitionTo() promise will be rejected with 
    // a 'transition prevented' error
})
  • $stateNotFound - v0.3.0 - fired when a requested state cannot be found using the provided state name during transition. The event is broadcast allowing any handlers a single chance to deal with the error (usually by lazy-loading the unfound state). A special unfoundState object is passed to the listener handler, you can see its three properties in the example. Use event.preventDefault() to abort the transition (transitionTo() promise will be rejected with a 'transition aborted' error). For a more in-depth example on lazy loading states, see How To: Lazy load states
// somewhere, assume lazy.state has not been defined
$state.go("lazy.state", {a:1, b:2}, {inherit:false});

// somewhere else
$rootScope.$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 - fired once the state transition is complete.狀態轉換完成後觸發。
$rootScope.$on('$stateChangeSuccess', 
function(event, toState, toParams, fromState, fromParams){ ... })
  • $stateChangeError - fired when an error occurs during transition. It's important to note that if you have any errors in your 

    相關推薦

    1Angular-Ui Router 狀態概要

    狀態管理器.新的狀態管理器($stateProvider) 類似於Angular's v1 的路由工作方式, 但更完美.A state corresponds to a "place" in the application in terms of the overall UI

    2Angular-Ui Router 巢狀狀態和巢狀檢視

    Methods for Nesting States巢狀狀態的方法States can be nested within each other. There are several ways of nesting states:狀態可以相互巢狀,巢狀狀態有幾種方法:Using

    ngRoute路由改變監聽事件(1)+ui.router狀態路由

    angular.module('myApp',['ngRoute'])     .config(['$routeProvider',function ($routeProvider) {         $routeProvider .when('/home',{                 templ

    angular-ui-router

    1-43 class att view desc asc 初始 config family 1.簡單示例 1 <html> 2 <head> 3 <title>ui-router</title>

    使用angular ui-router的一點感受

    一、背景 今年3月份從一個同事那裡接手了一個angular專案,心裡有血竊喜,自己花了兩個星期自學的angular終於可以用上戰場啦!不久,那個同事離職啦,整個專案落在了我的手裡,就在專案快要上線時,領導說,要加一點新的功能。想著又要加班啦,我心裡一萬隻草泥馬

    angular+ui-router+layui的使用心得

    近來,完成公司的一個專案,專案使用angular+ui-router+layui框架開發,由於剛剛接觸angularjs,因此遇到各種各樣的坑。在這裡記下印象最深的幾個坑; 一、ng-repeat 當陣列元素有至少兩個相同時,報Error: [ngRe

    angular-ui-router 多檢視views

    UI Router 中有三種方式啟用一個路由: (1)$state.go():優先順序較高的便利方式 (2)ui-sref:點選包含此指令跳轉 (3)url:url導航 一、$state.go() (1)$state.go(to [, toPa

    angular ui-router 路由預設跳轉語句$urlRouterProvider.otherwise(‘路徑');與共用時存在的問題

    當angular路由設定預設跳轉路徑$urlRouterProvider.otherwise(‘default'),並且頁面存在<a>標籤並且<a>標籤設定屬性href="###"即<a href="###></a>時,每次點

    Angularjs1.x+ocLazyLoad+angular-ui-router+ui-router-extras

    前言 總是聽人說angularjs的學習曲線很高,個人認為ng的難度是有的,但是要說難到哪裡,其實也不見得。總結來說,ng比較有難度的地方應當是路由和lazy載入。今天就把這部分內容通過一個小示例分享給大家。 依賴 專案包結構 程式碼

    Angular-ui-router進階二之巢狀檢視與多個檢視組合使用

    ui-router巢狀檢視 巢狀檢視是ui-router不同於ng-route的最大區別之一,也是ui-router受到大眾青睞的主要原因。接下來跟小編直接上手做一下簡單的巢狀檢視(Nested Views)。 上面是本次示例的佈局,有導航欄、側邊欄、檢視1及其子孫檢

    1接口測試概要和http基礎亂抄篇

    錯誤 性能 返回 存儲 並且 邊界值 技術分享 電商 請求 一、接口測試的要點: 圖片是抄襲的,但是自己還是要總結下要點:   1、檢查接口返回的數據是否與預期的一致;  2、檢查接口的容錯性,驗證傳遞錯誤的數據類型時,能否正常的處理;  3、接口參數的邊界值; 

    angular.js】UI-Routerangular路由學習

    分享 www. roo 多個 js框架 https angualrjs nbsp tool AngularJs中的路由,應用比較廣泛,主要是允許我們通過不同的url訪問不同的內容,可實現多視圖的單頁web應用。下面看看具體怎麽使用。 關於路由 通常我們的U

    1python腳本——監測服務器狀態

    python 運維 自動化監測服務器狀態獲取系統性能信息1、CPU信息: Linux操作系統的CPU利用的幾個部分:User Time;SystemTime;Wait IO;Idlepsutil.cpu_times()psutil.cpu_times().userpsutil.cpu_count()2、內存

    比亞迪開放平臺介面——1車身狀態

    BYDAutoBodyworkDevice 車身狀態類 方法概要 方法 描述 static BYDAutoBodyworkDevice getInstance(Context con) 獲取例項

    angularJs模組ui-router狀態巢狀和檢視巢狀

    狀態巢狀的方法 狀態可以相互巢狀。有三個巢狀的方法: 使用“點標記法”,例如:.state('contacts.list', {})使用parent屬性,指定一個父狀態的名稱字串,例如:parent: 'contacts'使用parent屬性,指定一個父狀態物件,例如

    angularJS+ui-router+requireJS非同步載入controllerdirectivefilter

    開發比較複雜的單頁面應用時,往往包括比較多的控制器、服務等,如果這些js檔案都在頁面開啟時就全部載入,往往載入量大,耗時長;因此,當開啟對應的頁面才載入響應的控制器等資源時,能一定程度地優化頁面載入速度。 · 專案目錄結構: · index.html:

    angular-ui/ui-router的使用

    前提環境(gulp+angular1) 第一步建立路由在路由頁面 'tabs.buyCart': { url: '/buyCart', views: { index:

    1TCL指令碼基本語法(概要

    TCL常用基本語法 一個TCL指令碼可以包含一個或多個命令。命令之間必須用換行符或分號隔開。 第一個單詞代表命令名,另外的單詞則是這個命令的引數,用空格或TAB鍵隔開。 變數置換$。 命令置換[] 反斜槓置換\ ,例如set msg multiple\ space ,如果沒

    AngularJS學習筆記--002--Angular JS路由外掛ui.router原始碼解析

    路由(route),幾乎所有的MVC(VM)框架都應該具有的特性,因為它是前端構建單頁面應用(SPA)必不可少的組成部分。 那麼,對於angular而言,它自然也有內建的路由模組:叫做ngRoute。 不過,大家很少用它,因為它的功能太有限,往

    Angular路由:ui-router

           ui-router是AngularJs的一個客戶端路由框架。AngularJs ngRoute模組中的路由是通過URL路由來管理檢視的,ui-router則是通過狀態(state)來管理檢視,並且可以繫結路由和其它的行為。狀態被繫結到命名、巢狀和並行檢視,大大