【问题标题】:using $rootScope in templateUrl function在 templateUrl 函数中使用 $rootScope
【发布时间】:2018-09-21 16:55:32
【问题描述】:

我刚开始使用 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 上声明了 utilisateur 的代码
  • 看起来 $rootScope 正在工作,但尚未定义 utilisateur。

标签: angularjs angularjs-scope


【解决方案1】:

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

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

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

  • /admin/home
  • /家

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

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>

不是理想的解决方案,但它适用于您正在尝试做的事情,基于您下面的 cmets

【讨论】:

  • 嗨;你能告诉我我该怎么做吗:我想使用相同的 URL (/home),但根据用户角色有不同的视图(例如,如果他的角色是管理员,我将他重定向到管理页面,否则我重定向他到主页,但两个页面应该有相同的路线(/home)。
  • 我认为理想的解决方案是有 2 条单独的路线: - /admin/home - /home 我假设你知道用户是否是管理员,只有在你的角度模块之后启动,因此您将无法修改配置块内的 $routeProvider 。如果不能选择 2 条单独的路由,您可以在“homeCtrl”内部检查是否为 isAdmin。在您看来,有 2 个 div 块。 &lt;div ng-if="isAdmin()"&gt;&lt;/div&gt;&lt;div ng-if="!isAdmin()"&gt;&lt;/div&gt;
  • 编辑了我上面的答案,以包括我之前评论中的可能选项。
【解决方案2】:

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

在您的视图中传递 url 中的参数(创建/编辑链接等)因为我在登录时设置了 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'
                        });.

参考链接swtiching views in routeProvider based on condition

【讨论】:

    【解决方案3】:

    下面的代码 sn-p 没有描述实现您想要的不同方法,而是回答了所提出的实际问题:

    如何在 templateUrl 函数中访问使用 $rootScope 定义的变量?

    上面的答案和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."; };
    });
    

    【讨论】:

      【解决方案4】:

      就像其他人说的,$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:'/'})
          ;
      }])
      
      ;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多