$stateProvider

来源:互联网 发布:au3.0录音软件 编辑:程序博客网 时间:2024/05/15 05:42

$stateProvider工作的方式与Angular's v1 router相近,但是他更加注重状态

  • 状态对应于应用程序中某个位置,整体的UI和导航A state corresponds to a "place" in the application in terms of the overall UI and navigation.
  • 状态通过控制器、模板、视图属性描述了UI和他的机制。
  • 状态通常都包含相同的东西,分解出这些共同点主要通过嵌套状态

最简单的例子

最简单的方式可以像这样添加

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <!-- in index.html -->  
  2. <body ng-controller="MainCtrl">  
  3. <section ui-view></section>  
  4. </body>  
  5.   
  6. // in app-states.js (or whatever you want to name it)  
  7. $stateProvider.state('contacts', {  
  8.   template: '<h1>My Contacts</h1>'  
  9. })  

Where does the template get inserted?

当状态被激活时,他的模板会被自动插入至他父状态的ui-view中。如果这是一个顶级状态,比如上例中contacts没有父状态,他的父模板就为index.html

眼下,'contacts'还不能被激活,让我们看看怎么激活这个状态

激活一个状态

有三种方式激活一个状态:

  1. 调用$state.go()方法Call $state.go(). 高层次的简单的方法. Learn More
  2. 点击ui-sref指示器中的链接 . Learn More
  3. 导航至state关联的url. Learn More.

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.

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. $stateProvider.state('contacts', {  
  2.   template: '<h1>My Contacts</h1>'  
  3. })  

Instead of writing the template inline you can load a partial. This is probably how you'll set templates most of the time.

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. $stateProvider.state('contacts', {  
  2.   templateUrl: 'contacts.html'  
  3. })  
templateUrl can also be a function that returns a url. It takes one preset parameter, stateParams, which is not injected.
[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. $stateProvider.state('contacts', {  
  2.   templateUrl: function (stateParams){  
  3.     return '/partials/contacts.' + stateParams.filterBy + '.html';  
  4.   }  
  5. })  
Or you can use a template provider function which can be injected, has access to locals, and must return template HTML, like this:
[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. $stateProvider.state('contacts', {  
  2.   templateProvider: function ($timeout, $stateParams) {  
  3.     return $timeout(function () {  
  4.       return '<h1>' + $stateParams.contactId + '</h1>'  
  5.     }, 100);  
  6.   }  
  7. })  
If you'd like your <ui-view> to have some default content before its 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.
[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <body>  
  2.     <ui-view>  
  3.         <i>Some content will load here!</i>  
  4.     </ui-view>  
  5. </body>  

Controllers

You can assign a controller to your template. Warning: The controller willnot be instantiated if template is not defined.

You set your controller like this:

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. $stateProvider.state('contacts', {  
  2.   template: '<h1>{{title}}</h1>',  
  3.   controller: function($scope){  
  4.     $scope.title = 'My Contacts';  
  5.   }  
  6. })  

Or if you already have a controller defined on the module, like this:

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. $stateProvider.state('contacts', {  
  2.   template: ...,  
  3.   controller: 'ContactsCtrl'  
  4. })  

Or use controllerAs syntax if preferred:

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. $stateProvider.state('contacts', {  
  2.   template: ...,  
  3.   controller: 'ContactsCtrl as contact'  
  4. })  

Or for more advanced needs you can use the controllerProvider to dynamically return a controller function or string for you:

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. $stateProvider.state('contacts', {  
  2.   template: ...,  
  3.   controllerProvider: function($stateParams) {  
  4.       var ctrlName = $stateParams.type + "Controller";  
  5.       return ctrlName;  
  6.   }  
  7. })  

Controllers can use the $scope.on() method to listen for events fired by state transitions.

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.

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.

If any of these dependencies are promises, they will be resolved and converted to a valuebefore the controller is instantiated and the $routeChangeSuccess event is fired.

The resolve property is a map object. The map object contains key/value pairs of:

  • key – {string}: a name of a dependency to be injected into the controller.
  • 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.

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. $stateProvider.state('myState', {  
  2.       resolve:{  
  3.   
  4.          // Example using function with simple return value.  
  5.          // Since it's not a promise, it resolves immediately.  
  6.          simpleObj:  function(){  
  7.             return {value: 'simple!'};  
  8.          },  
  9.   
  10.          // Example using function with returned promise.  
  11.          // This is the typical use case of resolve.  
  12.          // You need to inject any services that you are  
  13.          // using, e.g. $http in this example  
  14.          promiseObj:  function($http){  
  15.             // $http returns a promise for the url data  
  16.             return $http({method: 'GET', url: '/someUrl'});  
  17.          },  
  18.   
  19.          // Another promise example. If you need to do some   
  20.          // processing of the result, use .then, and your   
  21.          // promise is chained in for free. This is another  
  22.          // typical use case of resolve.  
  23.          promiseObj2:  function($http){  
  24.             return $http({method: 'GET', url: '/someUrl'})  
  25.                .then (function (data) {  
  26.                    return doSomeStuffFirst(data);  
  27.                });  
  28.          },          
  29.   
  30.          // Example using a service by name as string.  
  31.          // This would look for a 'translations' service  
  32.          // within the module and return it.  
  33.          // Note: The service could return a promise and  
  34.          // it would work just like the example above  
  35.          translations: "translations",  
  36.   
  37.          // Example showing injection of service into  
  38.          // resolve function. Service then returns a  
  39.          // promise. Tip: Inject $stateParams to get  
  40.          // access to url parameters.  
  41.          translations2: function(translations, $stateParams){  
  42.              // Assume that getLang is a service method  
  43.              // that uses $http to fetch some translations.  
  44.              // Also assume our url was "/:lang/home".  
  45.              translations.getLang($stateParams.lang);  
  46.          },  
  47.   
  48.          // Example showing returning of custom made promise  
  49.          greeting: function($q, $timeout){  
  50.              var deferred = $q.defer();  
  51.              $timeout(function() {  
  52.                  deferred.resolve('Hello!');  
  53.              }, 1000);  
  54.              return deferred.promise;  
  55.          }  
  56.       },  
  57.   
  58.       // The controller waits for every one of the above items to be  
  59.       // completely resolved before instantiation. For example, the  
  60.       // controller will not instatiate until promiseObj's promise has   
  61.       // been resolved. Then those objects are injected into the controller  
  62.       // and available for use.    
  63.       controller: function($scope, simpleObj, promiseObj, promiseObj2, translations, translations2, greeting){  
  64.           $scope.simple = simpleObj.value;  
  65.   
  66.           // You can be sure that promiseObj is ready to use!  
  67.           $scope.items = promiseObj.items;  
  68.           $scope.items = promiseObj2.items;  
  69.   
  70.           $scope.title = translations.getLang("english").title;  
  71.           $scope.title = translations2.title;  
  72.   
  73.           $scope.greeting = greeting;  
  74.       }  
  75.    })  

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).

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. // Example shows an object-based state and a string-based state  
  2. var contacts = {   
  3.     name: 'contacts',  
  4.     templateUrl: 'contacts.html',  
  5.     data: {  
  6.         customData1: 5,  
  7.         customData2: "blue"  
  8.     }    
  9. }  
  10. $stateProvider  
  11.   .state(contacts)  
  12.   .state('contacts.list', {  
  13.     templateUrl: 'contacts.list.html',  
  14.     data: {  
  15.         customData1: 44,  
  16.         customData2: "red"  
  17.     }   
  18.   })  
With the above example states you could access the data like this:
[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. function Ctrl($state){  
  2.     console.log($state.current.data.customData1) // outputs 5;  
  3.     console.log($state.current.data.customData2) // outputs "blue";  
  4. }  

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.

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. $stateProvider.state("contacts", {  
  2.   template: '<h1>{{title}}</h1>',  
  3.   resolve: { title: 'My Contacts' },  
  4.   controller: function($scope, title){  
  5.     $scope.title = 'My Contacts';  
  6.   },  
  7.   onEnter: function(title){  
  8.     if(title){ ... do something ... }  
  9.   },  
  10.   onExit: function(title){  
  11.     if(title){ ... do something ... }  
  12.   }  
  13. })  

State Change Events

All these events are fired at the $rootScope level.

  • $stateChangeStart - fired when the transition begins.
    [javascript] view plaincopy在CODE上查看代码片派生到我的代码片
    1. $rootScope.$on('$stateChangeStart',   
    2. function(event, toState, toParams, fromState, fromParams){ ... })  
    Note: Use event.preventDefault() to prevent the transition from happening.
    [javascript] view plaincopy在CODE上查看代码片派生到我的代码片
    1. $rootScope.$on('$stateChangeStart',   
    2. function(event, toState, toParams, fromState, fromParams){   
    3.     event.preventDefault();   
    4.     // transitionTo() promise will be rejected with   
    5.     // a 'transition prevented' error  
    6. })  
  • $stateNotFound - v0.3.0 - fired when a requested statecannot 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 specialunfoundStateobject is passed to the listener handler, you can see its three properties in the example. Useevent.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, seeHow To: Lazy load states
    [javascript] view plaincopy在CODE上查看代码片派生到我的代码片
    1. // somewhere, assume lazy.state has not been defined  
    2. $state.go("lazy.state", {a:1, b:2}, {inherit:false});  
    3.   
    4. // somewhere else  
    5. $scope.$on('$stateNotFound',   
    6. function(event, unfoundState, fromState, fromParams){   
    7.     console.log(unfoundState.to); // "lazy.state"  
    8.     console.log(unfoundState.toParams); // {a:1, b:2}  
    9.     console.log(unfoundState.options); // {inherit:false} + default options  
    10. })  
  • $stateChangeSuccess - fired once the state transition is complete.
    [javascript] view plaincopy在CODE上查看代码片派生到我的代码片
    1. $rootScope.$on('$stateChangeSuccess',   
    2. function(event, toState, toParams, fromState, fromParams){ ... })  
  • $stateChangeError - fired when an error occurs during transition.
    [javascript] view plaincopy在CODE上查看代码片派生到我的代码片
    1. $rootScope.$on('$stateChangeError',   
    2. function(event, toState, toParams, fromState, fromParams, error){ ... })  

View Load Events

  • $viewContentLoading - fired once the view begins loading,before the DOM is rendered. The '$scope' broadcasts the event.

    [javascript] view plaincopy在CODE上查看代码片派生到我的代码片
    1. $scope.$on('$viewContentLoading',   
    2. function(event, viewConfig){   
    3.     // Access to all the view config properties.  
    4.     // and one special property 'targetView'  
    5.     // viewConfig.targetView   
    6. });  
  • $viewContentLoaded - fired once the view is loaded,after the DOM is rendered. The '$scope' of the view emits the event.

    [javascript] view plaincopy在CODE上查看代码片派生到我的代码片
    1. $scope.$on('$viewContentLoaded',

1 0