在templateUrl函数中使用$ rootScope [英] using $rootScope in templateUrl function

查看:65
本文介绍了在templateUrl函数中使用$ rootScope的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用angularJS,但我有一个问题: 如何访问templateUrl函数中用$ rootScope定义的变量? 这是我的代码:

I just started with angularJS and I have a question: How can I access a variable defined with $rootScope in a templateUrl function? Here is my code:

myApp.config(['$routeProvider',
            function($routeProvider, $rootScope) {
              $routeProvider.
                when( '/', {
                  templateUrl: 'partials/login.html',
                  controller: 'loginCtrl'
                }).
                when( '/home', {
                  templateUrl: function($rootScope){
                      console.log($rootScope.utilisateur.user.role_id);
                      if ($rootScope.utilisateur.user.role_id==2){
                      return  'partials/home.html';
                      }
                      else return 'partials/login.html';
                  },
                  controller: 'homeCtrl'
                }).
                otherwise({redirectTo:'/'});
            }]);

它告诉我utilisateur是未定义的.

It tells me that utilisateur is undefined.

我在索引控制器中定义了它:

I defined it in the index controller:

$rootScope.utilisateur = null;
$rootScope.rapports = null;

然后在LoginCtrl中:

And then in the LoginCtrl:

 var user = Authentification.login(email,password);
    user.success(function(response){
        $rootScope.utilisateur = response;
        console.log($rootScope.utilisateur);
        $location.path('/home');
    });

推荐答案

您不能在config块中使用$ rootScope,因为config块在创建$ rootScope之前运行.可以在config块内部使用常量和提供程序.如果常量不是您的选择,则可能需要重定向到homeCtrl内部的正确网址.

You cannot use the $rootScope inside of the config block, as the config block runs before the $rootScope is created. Constants and providers may be used inside of the config block instead. If constants are not an option for you, you may want to redirect to the correct url inside of your homeCtrl.

从下面的注释中添加了可能的解决方案:

Added possible solution from comment below:

选项1:有2条不同的路线

Option 1: Have 2 different routes

  • /admin/home
  • /home

选项2:根据控制器/视图内部的权限切换模板

Option 2: Switch templates according to permission inside of controller/view

home.html

home.html

<div ng-switch="utilisateur.user.role_id">
    <div ng-switch-when="2">
    <!-- is admin -->
    </div>
    <div ng-switch-default>
    <!-- not admin -->
    </div>
</div>

这不是理想的解决方案,但根据您的以下评论,它可以满足您的尝试

Not the ideal solution, but it'd work for what you are trying to do, based on your comments below

这篇关于在templateUrl函数中使用$ rootScope的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆