Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
wmuisnan edited this pageJul 7, 2017 ·137 revisions

Next (Nested States & Nested Views) ►

This In-Depth Guide will take you through all aspects of the UI-Router and its components and options. If you just need a quick reference guide visit theAPI Reference

State Manager.

The new$stateProvider works similar to Angular's v1 router, but it focuses purely on state.

  • A state corresponds to a "place" in the application in terms of the overall UI and navigation.
  • A state (via the controller / template / view properties) describes what the UI looks like and does at that place.
  • 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 withinmodule.config):

<!-- in index.html --><bodyng-controller="MainCtrl"><sectionui-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 theui-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.

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
  2. Click a link containing theui-sref directive.Learn More
  3. Navigate to theurl associated with the state.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 thetemplate config property.

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

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

$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:

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

<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 willnot be instantiated if template is not defined.

You set yourcontroller like this:

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

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

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

Alternatively using the "controller as" syntax the above becomes:

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

and

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

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

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

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 useresolve 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 $stateChangeSuccess event is fired.

Theresolve 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 inresolve below must be resolved (viadeferred.resolve() if they are a promise) before thecontroller is instantiated. Notice how each resolve object is injected as a parameter into the controller.

$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 examplepromiseObj:function($http){// $http returns a promise for the url datareturn$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){returndoSomeStuffFirst(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 abovetranslations:"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".returntranslations.getLang($stateParams.lang);},// Example showing returning of custom made promisegreeting:function($q,$timeout){vardeferred=$q.defer();$timeout(function(){deferred.resolve('Hello!');},1000);returndeferred.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 adata property to avoid conflicts).

// Example shows an object-based state and a string-based statevarcontacts={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:

functionCtrl($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.

$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){ ...dosomething ...}},onExit:function(title){if(title){ ...dosomething ...}}})

State Change Events

NOTE: State change events are deprecated, DISABLED and replaced by Transition Hooks as of version 1.0 (details)

All these events are fired at the$rootScope level.

  • $stateChangeStart - fired when the transitionbegins.
$rootScope.$on('$stateChangeStart',function(event,toState,toParams,fromState,fromParams,options){ ...})

Note: Use event.preventDefault() to prevent the transition from happening.

$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 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 specialunfoundState object 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
// 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 iscomplete.
$rootScope.$on('$stateChangeSuccess',function(event,toState,toParams,fromState,fromParams){ ...})
  • $stateChangeError - fired when anerror occurs during transition. It's important to note that if you have any errors in yourresolve functions (javascript errors, non-existent services, etc) they will not throw traditionally. You must listen for this $stateChangeError event to catch ALL errors. Useevent.preventDefault() to prevent the $UrlRouter from reverting the URL to the previous valid location (in case of a URL navigation).
$rootScope.$on('$stateChangeError',function(event,toState,toParams,fromState,fromParams,error){ ...})

View Load Events

  • $viewContentLoading - fired once the viewbegins loading,before the DOM is rendered. The '$rootScope' broadcasts the event.
$rootScope.$on('$viewContentLoading',function(event,viewConfig){// Access to all the view config properties.// and one special property 'targetView'// viewConfig.targetView});
  • $viewContentLoaded - fired once the view isloaded,after the DOM is rendered. The '$scope' of the view emits the event.
$scope.$on('$viewContentLoaded',function(event){ ...});

Next (Nested States & Nested Views) ►

Clone this wiki locally

[8]ページ先頭

©2009-2025 Movatter.jp