using $rootScope in templateUrl function

2019-07-19 15:23发布

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:'/'});
            }]);

It tells me that utilisateur is undefined.

I defined it in the index controller:

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

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');
    });

4条回答
劳资没心,怎么记你
2楼-- · 2019-07-19 15:57

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.

[EDIT] Added possible solution from comment below:

Option 1: Have 2 different routes

  • /admin/home
  • /home

Option 2: Switch templates according to permission inside of 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>

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

查看更多
孤傲高冷的网名
3楼-- · 2019-07-19 16:00

Your problem seems like you have two different views, and on condition base you have to redirect views.

Pass the parameters in url like from your views (Create/Edit link etc.) As i have set the cookie on login and accessed here as a parameters or you can use different way to access the parameters.

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

And your config in $routeProvider use like this:

   $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'
                        });.

Refere a link swtiching views in routeProvider based on condition

查看更多
Bombasti
4楼-- · 2019-07-19 16:14

Like others have said, $rootScope doesn't exist yet, but unlike their answers, it doesn't at all mean you can't use it at all, you just have to code-in the wait.

Here is your example working but just printing since we dont have the templates.

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:'/'})
    ;
}])

;
查看更多
萌系小妹纸
5楼-- · 2019-07-19 16:24

Instead of describing different ways to achieve what you would like to, the code snippet below answers the actual question that was asked:

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

The answers above and here imply there is no way to reference $rootScope within the config/$routeProvider. While that may strictly be true, there is a simple way to access the $rootScope through $routeProvider. Below is how to do this:

Sample 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>

Sample 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."; };
});
查看更多
登录 后发表回答