Access routeProvider's route properties

吃可爱长大的小学妹 提交于 2019-12-31 22:48:09

问题


For a route defined like this:

$routeProvider
.when('/',
{
    templateUrl:'views/login.html',
    controller:'Login',
    private:false
});

How can I access the private property inside a $routeChangeStart event for example? Currently I'm using current.$$route.private to get it, but it seems wrong.

Thanks.


回答1:


It is actually recommended to put all your custom data with routes inside a "data" object as such.

$routeProvider
.when('/',
{
    templateUrl:'views/login.html',
    controller:'Login',
    data: {
       private: false
    }
});

Here is how I access route params

$rootScope.$on( "$routeChangeStart", function(event, next, current) {
   next.data.private;
});

The second parameter of the routeChangeStart event is the route object that is called. Another advantage is that anything in the data object is passed to children states.




回答2:


$routeChangeStart happens prior to the route changing, so you need to look at next. There's no need to use next.$$route since next inherits from $$route.

angular.module('example', ['ngRoute'])
  .config(function($routeProvider) {
    $routeProvider.when('/',  {
      controller: 'MyCtrl',
      template:   '<b>isPrivate: {{isPrivate}}</b>',

      private: false
    });
  })

  .run(function($rootScope) {
    $rootScope.$on('$routeChangeStart', function(event, next, current) {
      /* 
       * this is fired prior to the route changing, so your params will be on
       * next.  Here we just attach it $rootScope as an example.
       * note that you don't need to use next.$$route since $$route is private,
       * and next inherits from next.$$route. */
       */
      $rootScope.isPrivate = next['private'];
    });
  })
  .controller('MyCtrl', function($scope) {

  })


来源:https://stackoverflow.com/questions/19862396/access-routeproviders-route-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!