将参数从routeProvider传递给控制器

时间:2014-05-12 13:46:24

标签: angularjs

我想将一个对象传递给我的控制器,这样我就可以在控制器触发时获得一组上下文元素。我基本上试图在配置文件中为我的路由配置每个控制器的元信息。

例如。 (我想创建一个meta并以某种方式将它注入控制器......

//In config.js
routes["/dashboard"] =  { 

          controller: 'controllers.DashboardController', 
           templateUrl: 'templates/dashboard.html',
           meta: {
                title: "My Title",
                description: "My Desc"

            }

         };


//In dashboard.js

controllers.DashboardController = function ($scope, $location, Page) {
    'use strict';
    Page.setTitle(meta.title); // Pull this from content coming in
    Page.setDescription(meta.description);

2 个答案:

答案 0 :(得分:1)

这就是我最终的结果......它优雅地工作......

在我的配置中

  //Route configurations
routes["/dashboard"] =  { 

         controller: 'controllers.DashboardController', 
         templateUrl: 'templates/dashboard.html', 
         meta: {
           title: "Dashboard",
           description: 'This is my description'
         }

 };

应用程序代码

 application.config(['$routeProvider', '$locationProvider','cfg', function AppConfig($routeProvider, $locationProvider, cfg, $routeParams) {

     $locationProvider.html5Mode(true).hashPrefix('!');

 console.log(cfg);
 for (var route in cfg.routes)  
     $routeProvider.when(route, cfg.routes[route]);

...

application.run(['$rootScope','Page', function($rootScope, Page) {


    $rootScope.$on('$routeChangeSuccess', function(event, current, previous) {

        Page.setTitle(current.$$route.meta.title); // Pull this from content coming in
        Page.setDescription(current.$$route.meta.title);
    });
}]);

...

 <title ng-bind="'my title &mdash; ' + Page.title()">My title </title>
    <meta name="description" content="{{Page.description()}}"/>

答案 1 :(得分:0)

我认为路线解析功能可以解决问题。

来自文档:

https://docs.angularjs.org/api/ngRoute/provider/ $ routeProvider

问题主题与示例:

Delaying AngularJS route change until model loaded to prevent flicker