如何用 Angularjs 的 ui-route 管理状态

时间 2016-03-19 16:19:24   っ凜風と舞雪に
主题  AngularJS

模板将被插入哪里?

状态被激活时,它的模板会自动插入到父状态对应的模板中包含ui-view属性的元素内部。如果是顶层的状态,那么它的父模板就是 index.html 。

激活状态

有三种方法来激活状态:

  1. 调用$state.go()方法,这是一个高级的便利方法。
  2. 点击包含ui-sref指令的链接。
  3. 导航到与状态相关联的 url。
Templates 模板

可以通过下面几种方法来配置一个状态的模板。 方法一:配置template属性,指定一段 HTML 字符串,这人是设置模板的最简单的方式。

$stateProvider.state(<spanclass="hljs-string">'contacts'</span>, {
  template: <spanclass="hljs-string">'<h1>My Contacts</h1>'</span>
})
 

方法二:配置 templateUrl 属性,来加载指定位置的模板,这是设置模板的常用方法。

$stateProvider.state(<spanclass="hljs-string">'contacts'</span>, {
  templateUrl: <spanclass="hljs-string">'contacts.html'</span>
})
 

templateUrl的值也可以是一个函数返回的url,函数带一个预设参数stateParams。 方法三:通过 templateProvider 函数返回模板的 HTML。

<spanclass="hljs-variable">$stateProvider</span>.state(<spanclass="hljs-string">'contacts'</span>, {
  templateProvider: <spanclass="hljs-function"><spanclass="hljs-keyword">function</span> <spanclass="hljs-params">(<spanclass="hljs-variable">$timeout</span>, <spanclass="hljs-variable">$stateParams</span>)</span> </span>{
    <spanclass="hljs-keyword">return</span> <spanclass="hljs-variable">$timeout</span>(<spanclass="hljs-function"><spanclass="hljs-keyword">function</span> <spanclass="hljs-params">()</span> </span>{
      <spanclass="hljs-keyword">return</span> <spanclass="hljs-string">'<h1>'</span> + <spanclass="hljs-variable">$stateParams</span>.contactId + <spanclass="hljs-string">'</h1>'</span>
    }, <spanclass="hljs-number">100</span>);
  }
})
 

如果想在状态被激活前,让<ui-view>有一些默认的内容,当状态被激活之后默认内容将被状态对应的模板替换。

<spanclass="hljs-tag"><<spanclass="hljs-title">body</span>></span>
    <spanclass="hljs-tag"><<spanclass="hljs-title">ui-view</span>></span>
        <spanclass="hljs-tag"><<spanclass="hljs-title">i</span>></span>Somecontentwillloadhere!<spanclass="hljs-tag"></<spanclass="hljs-title">i</span>></span>
    <spanclass="hljs-tag"></<spanclass="hljs-title">ui-view</span>></span>
<spanclass="hljs-tag"></<spanclass="hljs-title">body</span>></span>
 
Controllers 控制器

可以为模板指定一个控制器(controller)。警告:控制器不会被实例化如果模板没有定义。 设置控制器:

$stateProvider.state('contacts', {
  <spanclass="hljs-keyword">template</span>: '<h1>{{title}}</h1>',
  controller: function($scope){
    $scope.title = '<span class="hljs-type">My</span> <span class="hljs-type">Contacts</span>';
  }
})
 

如果在模块中已经定义了一个控制器,只需要指定控制器的名称即可:

$stateProvider.state(<spanclass="hljs-string">'contacts'</span>, {
  template: <spanclass="hljs-keyword">...</span>,
  controller: <spanclass="hljs-string">'ContactsCtrl'</span>
})
 

使用 controllerAs 语法:

$stateProvider.state(<spanclass="hljs-string">'contacts'</span>, {
  template: <spanclass="hljs-keyword">...</span>,
  controller: <spanclass="hljs-string">'ContactsCtrl as contact'</span>
})
 

对于更高级的需要,可以使用controllerProvider来动态返回一个控制器函数或字符串:

$stateProvider.state(<spanclass="hljs-string">'contacts'</span>, {
  template: <spanclass="hljs-keyword">...</span>,
  controllerProvider: <spanclass="hljs-keyword">function</span>($stateParams) {
      var ctrlName = $stateParams.type + <spanclass="hljs-string">"Controller"</span>;
      <spanclass="hljs-keyword">return</span> ctrlName;
  }
})
 

控制器可以使用 $scope.on() 方法来监听事件状态转换。 控制器可以根据需要实例化,当相应的 scope 被创建时。例如,当用户点击一个 url 手动导航一个状态时,$stateProvider 将加载对应的模板到视图中,并且将控制器和模板的 scope 绑定在一起。

解决器 Resolver

可以使用 resolver 为控制器提供可选的依赖注入项。 resolver 配置项是一个由key/value构成的对象。

  • key – {string}:注入控制器的依赖项名称。
  • factory – {string|function}:
    • string:一个服务的别名
    • function:函数的返回值将作为依赖注入项,如果函数是一个耗时的操作,那么控制器必须等待该函数执行完成(be resolved)才会被实例化。 
      例子

      在 controller 实例化之前,resolve 中的每一个对象都必须 be resolved,请注意每个 resolved object 是怎样作为参数注入到控制器中的。

      <spanclass="hljs-variable">$stateProvider</span>.state(<spanclass="hljs-string">'myState'</span>, {
        resolve:{
       
          <spanclass="hljs-comment">// Example using function with simple return value.</span>
          <spanclass="hljs-comment">// Since it's not a promise, it resolves immediately.</span>
          simpleObj:  <spanclass="hljs-function"><spanclass="hljs-keyword">function</span><spanclass="hljs-params">()</span></span>{
              <spanclass="hljs-keyword">return</span> {value: <spanclass="hljs-string">'simple!'</span>};
          },
       
          <spanclass="hljs-comment">// Example using function with returned promise.</span>
          <spanclass="hljs-comment">// 这是一种典型使用方式</span>
          <spanclass="hljs-comment">// 请给函数注入任何想要的服务依赖,例如 $http</span>
          promiseObj:  <spanclass="hljs-function"><spanclass="hljs-keyword">function</span><spanclass="hljs-params">(<spanclass="hljs-variable">$http</span>)</span></span>{
              <spanclass="hljs-comment">// $http returns a promise for the url data</span>
              <spanclass="hljs-keyword">return</span> <spanclass="hljs-variable">$http</span>({method: <spanclass="hljs-string">'GET'</span>, url: <spanclass="hljs-string">'/someUrl'</span>});
          },
       
          <spanclass="hljs-comment">// Another promise example. </span>
          <spanclass="hljs-comment">// 如果想对返回结果进行处理, 可以使用 .then 方法</span>
          <spanclass="hljs-comment">// 这是另一种典型使用方式</span>
          promiseObj2:  <spanclass="hljs-function"><spanclass="hljs-keyword">function</span><spanclass="hljs-params">(<spanclass="hljs-variable">$http</span>)</span></span>{
              <spanclass="hljs-keyword">return</span> <spanclass="hljs-variable">$http</span>({method: <spanclass="hljs-string">'GET'</span>, url: <spanclass="hljs-string">'/someUrl'</span>})
                .then (<spanclass="hljs-function"><spanclass="hljs-keyword">function</span> <spanclass="hljs-params">(data)</span> </span>{
                    <spanclass="hljs-keyword">return</span> doSomeStuffFirst(data);
                });
          },        
       
          <spanclass="hljs-comment">// 使用服务名的例子,这将在模块中查找名称为 'translations' 的服务,并返回该服务 </span>
          <spanclass="hljs-comment">// Note: The service could return a promise and</span>
          <spanclass="hljs-comment">// it would work just like the example above</span>
          translations: <spanclass="hljs-string">"translations"</span>,
       
          <spanclass="hljs-comment">// 将服务模块作为解决函数的依赖项,通过参数传入</span>
          <spanclass="hljs-comment">// 提示:依赖项 $stateParams 代表 url 中的参数</span>
          translations2: <spanclass="hljs-function"><spanclass="hljs-keyword">function</span><spanclass="hljs-params">(translations, <spanclass="hljs-variable">$stateParams</span>)</span></span>{
              <spanclass="hljs-comment">// Assume that getLang is a service method</span>
              <spanclass="hljs-comment">// that uses $http to fetch some translations.</span>
              <spanclass="hljs-comment">// Also assume our url was "/:lang/home".</span>
              translations.getLang(<spanclass="hljs-variable">$stateParams</span>.lang);
          },
       
          <spanclass="hljs-comment">// Example showing returning of custom made promise</span>
          greeting: <spanclass="hljs-function"><spanclass="hljs-keyword">function</span><spanclass="hljs-params">(<spanclass="hljs-variable">$q</span>, <spanclass="hljs-variable">$timeout</span>)</span></span>{
              <spanclass="hljs-keyword">var</span> deferred = <spanclass="hljs-variable">$q</span>.defer();
              <spanclass="hljs-variable">$timeout</span>(<spanclass="hljs-function"><spanclass="hljs-keyword">function</span><spanclass="hljs-params">()</span> </span>{
                  deferred.resolve(<spanclass="hljs-string">'Hello!'</span>);
              }, <spanclass="hljs-number">1000</span>);
              <spanclass="hljs-keyword">return</span> deferred.promise;
          }
        },
       
        <spanclass="hljs-comment">// 控制器将等待上面的解决项都被解决后才被实例化</span>
        controller: <spanclass="hljs-function"><spanclass="hljs-keyword">function</span><spanclass="hljs-params">(<spanclass="hljs-variable">$scope</span>, simpleObj, promiseObj, promiseObj2, translations, translations2, greeting)</span></span>{
       
            <spanclass="hljs-variable">$scope</span>.simple = simpleObj.value;
       
            <spanclass="hljs-comment">// 这里可以放心使用 promiseObj 中的对象</span>
            <spanclass="hljs-variable">$scope</span>.items = promiseObj.items;
            <spanclass="hljs-variable">$scope</span>.items = promiseObj2.items;
       
            <spanclass="hljs-variable">$scope</span>.title = translations.getLang(<spanclass="hljs-string">"english"</span>).title;
            <spanclass="hljs-variable">$scope</span>.title = translations2.title;
       
            <spanclass="hljs-variable">$scope</span>.greeting = greeting;
        }
      })
       
      
      为 $state 对象提供自定义数据

      可以给 $state 对象提供自定义数据(建议使用data属性,以免冲突)

      <spanclass="hljs-comment">// 基于对象和基于字符串定义 state 的例子</span>
      <spanclass="hljs-keyword">var</span> contacts = { 
      name: <spanclass="hljs-string">'contacts'</span>,
      templateUrl: <spanclass="hljs-string">'contacts.html'</span>,
      data: {
          customData1: <spanclass="hljs-number">5</span>,
          customData2: <spanclass="hljs-string">"blue"</span>
      }  
      }
      $stateProvider
      .state(contacts)
      .state(<spanclass="hljs-string">'contacts.list'</span>, {
      templateUrl: <spanclass="hljs-string">'contacts.list.html'</span>,
      data: {
          customData1: <spanclass="hljs-number">44</span>,
          customData2: <spanclass="hljs-string">"red"</span>
      } 
      })
       
      

      可以通过下面的方式来访问上面定义的数据:

      <spanclass="hljs-function"><spanclass="hljs-keyword">function</span> <spanclass="hljs-title">Ctrl</span><spanclass="hljs-params">(<spanclass="hljs-variable">$state</span>)</span></span>{
      console.log(<spanclass="hljs-variable">$state</span>.current.data.customData1) <spanclass="hljs-comment">// 输出 5;</span>
      console.log(<spanclass="hljs-variable">$state</span>.current.data.customData2) <spanclass="hljs-comment">// 输出 "blue";</span>
      }
       
      
      onEnter 和 onExit 回调函数

      onEnter和onExit回调函数是可选配置项,分别称为当一个状态变得活跃的和不活跃的时候触发。回调函数也可以访问所有解决依赖项。

      $stateProvider.state(<spanclass="hljs-string">"contacts"</span>, {
      template: <spanclass="hljs-string">'<h1>{{title}}</h1>'</span>,
      resolve: { title: <spanclass="hljs-string">'My Contacts'</span> },
      controller: <spanclass="hljs-keyword">function</span>($scope, title){
      $scope.title = <spanclass="hljs-string">'My Contacts'</span>;
      },
      // title 是解决依赖项,这里也是可以使用解决依赖项的
      onEnter: <spanclass="hljs-keyword">function</span>(title){ 
      <spanclass="hljs-keyword">if</span>(title){ <spanclass="hljs-keyword">...</span> do something <spanclass="hljs-keyword">...</span> }
      },
      // title 是解决依赖项,这里也是可以使用解决依赖项的
      onExit: <spanclass="hljs-keyword">function</span>(title){
      <spanclass="hljs-keyword">if</span>(title){ <spanclass="hljs-keyword">...</span> do something <spanclass="hljs-keyword">...</span> }
      }
      })
       
      
      State Change Events 状态改变事件

      所有这些事件都是在$rootScope作用域触发

  • $stateChangeStart – 当模板开始解析之前触发
    $rootScope.$on(<spanclass="hljs-string">'$stateChangeStart'</span>, 
    <spanclass="hljs-keyword">function</span>(event, toState, toParams, fromState, fromParams){ <spanclass="hljs-keyword">...</span> })
     
    

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

    <spanclass="hljs-variable">$rootScope</span>.<spanclass="hljs-variable">$on</span>(<spanclass="hljs-string">'$stateChangeStart'</span>, 
    <spanclass="hljs-function"><spanclass="hljs-keyword">function</span><spanclass="hljs-params">(event, toState, toParams, fromState, fromParams)</span></span>{ 
      event.preventDefault(); 
      <spanclass="hljs-comment">// transitionTo() promise will be rejected with </span>
      <spanclass="hljs-comment">// a 'transition prevented' error</span>
    })
     
    
  • $stateNotFound – v0.3.0 – 在 transition 时通过状态名查找状态,当状态无法找到时发生。该事件在 scope 链上广播,只允许一次处理错误的机会。unfoundState将作为参数传入事件监听函数,下面例子中可以看到unfoundState的三个属性。使用 event.preventDefault() 来阻止模板解析.
    // somewhere, assume lazy.<span class="hljs-keyword">state</span> has not been defined
    <spanclass="hljs-variable">$state</span>.go(<spanclass="hljs-string">"lazy.state"</span>, {a:<spanclass="hljs-number">1</span>, b:<spanclass="hljs-number">2</span>}, {inherit:false});
    // somewhere else
    <spanclass="hljs-variable">$scope</span>.<spanclass="hljs-variable">$on</span>('<span class="hljs-variable">$stateNotFound</span>', 
    function(event, unfoundState, <spanclass="hljs-keyword">from</span>State, <spanclass="hljs-keyword">from</span>Params){ 
      console.<spanclass="hljs-keyword">log</span>(unfoundState.<spanclass="hljs-keyword">to</span>); // <span class="hljs-string">"lazy.state"</span>
      console.<spanclass="hljs-keyword">log</span>(unfoundState.<spanclass="hljs-keyword">to</span>Params); // {a:<span class="hljs-number">1</span>, b:<span class="hljs-number">2</span>}
      console.<spanclass="hljs-keyword">log</span>(unfoundState.options); // {inherit:false} + <span class="hljs-keyword">default</span> options
    })
     
    
  • $stateChangeSuccess – 当模板解析完成后触发
    $rootScope.$on(<spanclass="hljs-string">'$stateChangeSuccess'</span>, 
    <spanclass="hljs-keyword">function</span>(event, toState, toParams, fromState, fromParams){ <spanclass="hljs-keyword">...</span> })
     
    
  • $stateChangeError – 当模板解析过程中发生错误时触发
    $rootScope.$on(<spanclass="hljs-string">'$stateChangeError'</span>, 
    <spanclass="hljs-keyword">function</span>(event, toState, toParams, fromState, fromParams, error){ <spanclass="hljs-keyword">...</span> })
     
    
View Load Events 视图加载事件
  • $viewContentLoading – 当视图开始加载,DOM渲染完成之前触发,该事件将在$scope链上广播此事件。
    <spanclass="hljs-variable">$scope</span>.<spanclass="hljs-variable">$on</span>(<spanclass="hljs-string">'$viewContentLoading'</span>, 
    <spanclass="hljs-function"><spanclass="hljs-keyword">function</span><spanclass="hljs-params">(event, viewConfig)</span></span>{ 
      <spanclass="hljs-comment">// Access to all the view config properties.</span>
      <spanclass="hljs-comment">// and one special property 'targetView'</span>
      <spanclass="hljs-comment">// viewConfig.targetView </span>
    });
     
    
  • $viewContentLoaded – 当视图加载完成,DOM渲染完成之后触发,视图所在的$scope发出该事件。
    $scope.$on(<spanclass="hljs-string">'$viewContentLoading'</span>, 
    $scope.$on(<spanclass="hljs-string">'$viewContentLoaded'</span>, 
    <spanclass="hljs-keyword">function</span>(event){ <spanclass="hljs-keyword">...</span> });
     
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
AngularJS `ui-view` 的使用通常涉及以下几个步骤: 1. 安装 AngularJSAngularUI Router。AngularUI Router 是一个用于 AngularJS 的第三方路由模块,可以实现多视图和嵌套路由等功能。 2. 在 HTML 中定义 `ui-view` 指令,用于展示视图。可以定义一个或多个 `ui-view`,每个指令可以使用一个名字来标识。 3. 在 JavaScript 中配置路由,并指定与视图相关的模板和控制器。通常使用 `$stateProvider` 和 `$urlRouterProvider` 服务来配置路由。 下面是一个简单的示例,演示了如何使用 `ui-view` 展示两个页面: ```html <!DOCTYPE html> <html ng-app="myApp"> <head> <meta charset="utf-8"> <title>AngularJS UI-Router Demo</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.29/angular-ui-router.min.js"></script> <script> // 创建 AngularJS 应用程序 var app = angular.module('myApp', ['ui.router']); // 配置路由 app.config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('home', { url: '/', templateUrl: 'home.html', controller: 'HomeController' }) .state('about', { url: '/about', templateUrl: 'about.html', controller: 'AboutController' }); $urlRouterProvider.otherwise('/'); }); // 控制器定义 app.controller('HomeController', function($scope) { $scope.message = 'Welcome to the homepage!'; }); app.controller('AboutController', function($scope) { $scope.message = 'Learn more about us!'; }); </script> </head> <body> <h1>AngularJS UI-Router Demo</h1> <nav> <a ui-sref="home">Home</a> <a ui-sref="about">About</a> </nav> <div ui-view></div> </body> </html> ``` 在上面的示例中,我们定义了两个路由:`home` 和 `about`。每个路由都指定了一个与之对应的模板和控制器。在 HTML 中,我们使用 `ui-sref` 指令来指定路由,并使用 `ui-view` 指令来展示视图。在这种情况下,我们只有一个 `ui-view`,因此没有必要给它指定任何名字。 当用户点击导航链接时,将会触发路由,对应的视图将会展示在 `ui-view` 中。在这个示例中,我们在 `HomeController` 和 `AboutController` 中定义了一些文本信息,用于展示在对应的视图中。 注意,使用 `ui-sref` 指令时,需要将路由名称作为参数传递给指令。这个名称应该与路由配置中的名称匹配。 这只是一个简单示例,实际应用中可能还需要更多的路由和视图。掌握了 `ui-view` 的基本使用方法之后,你可以继续学习 AngularUI Router 的更多功能,例如嵌套视图、路由参数等等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值