$stateProvider

2023-11-10

$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 plain copy 在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 plain copy 在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 plain copy 在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 plain copy 在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 plain copy 在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 plain copy 在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 plain copy 在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 plain copy 在CODE上查看代码片 派生到我的代码片
  1. $stateProvider.state('contacts', {  
  2.   template: ...,  
  3.   controller: 'ContactsCtrl'  
  4. })  

Or use controllerAs syntax if preferred:

   
   
[javascript] view plain copy 在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 plain copy 在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 plain copy 在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 plain copy 在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 plain copy 在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 plain copy 在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 plain copy 在CODE上查看代码片 派生到我的代码片
    1. $rootScope.$on('$stateChangeStart',   
    2. function(event, toState, toParams, fromState, fromParams){ ... })  
    Note: Use event.preventDefault() to prevent the transition from happening.
         
         
    [javascript] view plain copy 在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 plain copy 在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 plain copy 在CODE上查看代码片 派生到我的代码片
    1. $rootScope.$on('$stateChangeSuccess',   
    2. function(event, toState, toParams, fromState, fromParams){ ... })  
  • $stateChangeError - fired when an error occurs during transition.
         
         
    [javascript] view plain copy 在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 plain copy 在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 plain copy 在CODE上查看代码片 派生到我的代码片
    1. $scope.$on('$viewContentLoaded',

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

$stateProvider 的相关文章

随机推荐

  • python123习题集

    python123习题集 06函数 07集合 08列表元组 09集合 10字典 12随机数 06函数 二分法求平方根 tips 二分法求解思路 精度控制 import math n delta map eval input split de
  • 坑爹的jack-server

    平台 rk3288 安卓版本 android7 1 记录一次jack server编译踩坑之路 期间本人改端口 重装java 8 openjdk amd64 反正各种尝试搞了一周 人都给整郁闷了 网上各种方法都尝试遍了甚至重装了系统 1 重
  • 中科院三院士谈AI:人工智能的“脑洞”有多大?

    李德毅 中国工程院院士 中国人工智能学会理事长 我们今天的科学家 尤其是计算机科学家 把 计算 用得太狠了 对 计算 的依赖甚至有些 贪得无厌 了 人工智能学者不能只盯着计算认知 一味要求 人脑研究的步伐有多快 而要拿出更多的精力放在 记忆
  • QT修改ui界面后显示的还是原来的界面

    这个问题可能是由于你从其他地方复制来了源码或者是ui界面 导致 ui xxx h 头文件不能及时更新导致的 只需要将工程的编译目录 工程的编译目录不一定是你的文件所在的目录 下的ui xxx h文件全部删除 在重新编译即可 如果不行的话就将
  • 面向对象——this关键字

    this关键字简介 当创建一个对象成功后 在构造方法调用前 对象已经创建成功 虚拟机 JVM 会动态的分配一个引用 该引用指向的就是当前对象 这个引用的名字叫做this 在成员方法中 谁调用这个方法 那么this就指向那个对象 在构造方法中
  • (Java毕业设计)房产销售管理系统(java+mysql)

    大家好 我是职场程序猿 感谢您阅读本文 欢迎一键三连哦 当前专栏 Java毕业设计 目录 一 项目简介 二 系统项目部分截图 2 1注册登陆功能 2 2公告信息功能 2 3房屋信息展示 2 4系统管理员功能 三 论文目录 四 部分核心代码
  • nodejs中require的路径是一个文件夹时发生了什么

    node中使用require的时候如果路径是一个文件夹时 或者特殊的情况require require 这是node实战这本书里说的情况 但是我在node6 9版本中发现不完全是这样 可能是后来做了修改 下面说说在6 9下require路径
  • 基础算法:浮点二分——数的三次方根

    浮点数二分 求一个数的三次方根 include
  • 蓝桥杯打卡Day1

    文章目录 全排列 八皇后 一 全排列IO链接 本题思路 本题是一道经典的全排列问题 深度优先搜索即可解决 include
  • helm简介、安装、配置、使用指南

    转载自 https blog csdn net bbwangj article details 81087911 目录 helm简介 Helm 组件及相关术语 Helm Tiller Chart Repoistory Release Hel
  • H2支持mysql:MODE=MySQL

    连接字符串参数 DB CLOSE DELAY 要求最后一个正在连接的连接断开后 不要关闭数据库 MODE MySQL 兼容模式 H2兼容多种数据库 该值可以为 DB2 Derby HSQLDB MSSQLServer MySQL Oracl
  • 在 MySQL 中,如果要存储大文本数据,改如何选择

    在 MySQL 中 如果要存储大文本数据 可以选择以下两种数据类型 TEXT 适用于存储较长的文本数据 最大长度为65 535个字符 LONGTEXT 适用于存储非常大的文本数据 最大长度为4 294 967 295个字符 选择使用哪种类型
  • 【SQL】sql语句LEFT JOIN(拼接表)详解

    1 语法 SELECT column name s FROM table1 LEFT JOIN table2 ON table1 column name table2 column name 2 说明 按照一定规则 将表table1和表ta
  • Python——将字符串写入文本保存

    sResult为要写入的内容 一般是字符串形式 with open C Python37 911 txt w encoding utf 8 as f f write str sResult f close
  • stm32 利用定时器中断消除按键抖动

    button c int iButtonCount i代表int型变量 ButtonCount表示按键计数变量 int iButtonFlag i代表int型变量 ButtonFlag表示重按键标志 1代表重新按键 0为没有重新按键 int
  • Android studio的cMake编译生成.so库并调用

    第一步 添加工具 在SDK Tools中勾选安装CMake LLDB NDK 其中的LLDB是调试本地代码的工具 可以调试C 代码 第二步 创建一个最简单的官方demo File gt New gt NewProject 选中最下方的Inc
  • 前端实战系列:如何开发微信小程序

    课程简介 小程序开发相对于App开发 开发快捷推广成本低 依托微信平台非常好推广 市面上很多企业现在都想开发自己的小程序 本次课程带大家开发一个小程序 从账号注册到编写全流程讲解 实现一个 本地生活案例 课程推荐 前端实战 如何开发微信小程
  • React 高频面试题-大厂必问

    React 对于react的理解 一 是什么 React 用于构建用户界面的JavaScript库 只提供UI层面的解决方案 遵循组件设计模式 声明式编程范式和函数式编程概念 以使前端应用程序更高效 使虚拟 DOM 来有效的操作 DOM 遵
  • C#(64位系统) 解决"未能加载文件或程序集,或它的某一个依赖项..."

    这个问题通常出在引用第三方DLL或者自己以前写的DLL 在64位系统下则可能会出现这种问题 今天下载MySQLDriverCS后引用遍出现了这个问题 参考了一些文档 下面给出解决方法 将项目的生成目标平台改为x86 默认Any cpu 就可
  • $stateProvider

    stateProvider工作的方式与Angular s v1 router相近 但是他更加注重状态 状态对应于应用程序中某个位置 整体的UI和导航A state corresponds to a place in the applicat