如何在视图中访问$ rootScope(cshtml)

时间:2019-01-08 08:37:11

标签: angularjs

我有以下代码

...
...
...
if (response.data) {
    console.log("response data was not null");
    if (response.data != null) {
        $rootScope.permissions = response.data.permissions;
        console.log("permissions: ", $rootScope.permissions);
        localStorage.setItem("UserPermissions", JSON.stringify($rootScope.permissions));        
...
...
...

,我想根据权限隐藏<li>标签。我已经尝试了多种方法,但未能找到解决方案。 在线阅读有关如何使用rootScope的内容,我遇到了一些使用$root的解决方案的帖子,但也没有用。

<div class="hidden-sm hidden-xs" style="text-align: center;">
    <ul class="header-menu">
        <li ng-if="$root.permissions[1].includes('permissionName')"><a ng-class="{ activeMenuItem: isActive('/Cases')}" ui-sref="Caes" class="current">My Cases<span class="count-wrap" ng-show="getCases() > 0" ng-bind="getCaseCount()" ng-cloak></span></a></li>
        <li ng-if="permissions[1].includes('permissionName')"><a ng-class="{ activeMenuItem: isActive('/Lawyers')}" ui-sref="Lawyers" class="current">My Lawyers<span class="count-wrap" ng-show="Law.Lawyer > 0" ng-bind="Law.LawyerCount" ng-cloak></span></a></li>
    </ul>
</div>

创建摘要有些困难,但是如果有更好的方法或者做错了,我正在寻找指导。

3 个答案:

答案 0 :(得分:0)

您无需在ypur视图中指定$ rootScope。 您可以像使用$ scope变量一样使用它。

var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope,$rootScope) {
    //set permissions to rootScope
    $rootScope.permissions=[{name:"permission 1",isActive:true},{name:"permission 2",isActive:false}]

});
	
	
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

	<div class="hidden-sm hidden-xs" style="text-align: center;">
		<ul class="header-menu">
			<li ng-repeat="permission in permissions">
			<a ng-if="permission.isActive">{{permission.name}} is Active<span class="count-wrap" ng-show="getCases() > 0" ng-bind="getCaseCount()" ng-cloak></span></a>
			<a  ng-if="!permission.isActive">{{permission.name}} is Not Active<span class="count-wrap" ng-show="getCases() > 0" ng-bind="getCaseCount()" ng-cloak></span></a>
			</li>			
		</ul>
	</div>

</div>

答案 1 :(得分:0)

在应用程序中遇到此问题时,也为了在视图中更新值,我使用了吸气剂功能来获取控制器中的$rootScope值(我习惯于命名控制器,但如果您不这样做, 't,只需删除ctrl.):

在视图中:

<li ng-if="ctrl.getPermissions()[1].includes('permissionName')">...

在控制器功能中:

function ctrlFunc($rootScope) {
    this.getPermissions = function(){ //or whatever way you use to define your functions, with $scope or this
        return $rootScope.permissions;
    };
}

答案 2 :(得分:0)

尝试:

ng-if="::$root.permissions.length > 1 && ::$root.permissions[1].includes('permissionName')"