在 templateUrl 函数中使用 $rootScope

using $rootScope in templateUrl function

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

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 未定义。

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

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

然后在LoginCtrl中:

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

您不能在配置块内使用 $rootScope,因为配置块在创建 $rootScope 之前运行。可以在配置块内部使用常量和提供程序。如果常量不适合您,您可能希望重定向到 homeCtrl 中正确的 url。

[编辑] 从下面的评论中添加了可能的解决方案:

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

  • /admin/home
  • /家

方案二:根据controller/view

内权限切换模板

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>

不是理想的解决方案,但根据您在下方的评论,它可以满足您的要求

您的问题似乎是您有两个不同的视图,并且根据条件您必须重定向视图。

传递 url 中的参数,例如您的视图(Create/Edit link 等)因为我在登录时设置了 cookie 并在此处作为参数访问,或者您可以使用访问参数的不同方式。

'<a href="#/editTest/{{model._id}}/' + getCookie(escape('cformview'))+ '" title="Edit Test"></a>'

你在 $routeProvider 中的配置是这样使用的:

   $routeProvider.when("/editTest/:ID/:flagTab",
                        {                               
                             templateUrl: function (params) {
                                var flag = params.flagTab;                                    
                                if (flag == 'tabPanelView') {
                                    return '/apps/templates/editTest.html';
                                }
                                else {
                                    return '/apps/templates/editTestPageView.html';
                                }                                    
                            },
                            controller: 'EditTestController'
                        });.

引用 link

下面的代码片段没有描述实现您想要的目标的不同方法,而是回答了实际提出的问题:

How can I access a variable defined with $rootScope in a templateUrl function?

上面的答案和 here 暗示无法在 config/$routeProvider 中引用 $rootScope。虽然这可能严格来说是正确的,但有一种简单的方法可以通过 $routeProvider 访问 $rootScope。以下是如何做到这一点:

样本HTML:

<div ng-app="myApp">
  <div ng-controller="masterController">
      <script type="text/ng-template" id="home.html">{{something}}</script>
      <a href="#page">Page</a>
      <div ng-view></div>
  </div>
</div>

样本javascript:

var myApp = angular.module('myApp',[],function($routeProvider) {        

$routeProvider
    .when('/home',{templateUrl:'home.html'})
    .when('/page',
    {
      template:'<p>{{something}}</p>', 
      controller:'masterCtrlWrapper'
    })
    .otherwise({redirectTo:'/home'});
});

myApp.controller('masterCtrlWrapper', function($rootScope)
{   $rootScope.changeVariable(); }); 

myApp.controller('masterController', function($rootScope)
{
  $rootScope.something = 'This is the $rootScope talking.'
  $rootScope.pressCount = 0;
  $rootScope.changeVariable = function()
  { $rootScope.something = "This function was run " + $rootScope.pressCount++ + " times."; };
});

就像其他人所说的那样,$rootScope 还不存在,但与他们的答案不同,这并不意味着你根本不能使用它,你只需要在等等。

Here is your example working 但只是打印,因为我们没有模板。

myApp

.provide('home', function() {
    var $rootScope = null;

    this.templateUrl = function() {
        var check =
            $rootScope.utilisateur &&
            $rootScope.utilisateur.user.role_id
        ;

        console.log(check);
        return (check) ? 'partials/home.html' : 'partials/login.html';
    };
    this.controller = 'homeCtrl';
    this.resolve = {load:['$rootScope', function(fetched) { $rootScope = fetched; }]};

    this.$get = function() { };
})

.config(['$routeProvider', 'homeProvider', function($routeProvider, homeProvider) {
    $routeProvider
        .when('/', {
            templateUrl : 'partials/login.html',
            controller  : 'loginCtrl'
        })
        .when('/home', homeProvider)
        .otherwise({redirectTo:'/'})
    ;
}])

;