使用函数传递ng-show的参数

时间:2015-01-07 18:26:59

标签: angularjs

我有一个菜单,我想根据登录用户的读写访问权限在菜单中隐藏某些li。

这是html:

<nav>
  <ul class="menu">
    <li><a href="#" id="adminLink">Admin</a>
        <ul>
            <li><a href="#/config">Configuration</a></li>
            <li ng-show="showPage('CRM Read')"><a id="crmLink" href="#/crm">CRM</a></li>
            <li><a id="rbacLink" href="#/rbac">RBAC</a></li>
        </ul>
    </li>
    <li><a href="#/dashboard">Dashboard</a></li>
      <li style="position: absolute; left: 90%;"><a href="#/security/logout" >Logout</a></li>
  </ul>
 </nav>

以下是功能:

 $scope.showIfAuthorized = function(checkRole) {
        var checkRole = checkRole;
        var checkingRole = AuthService.hasRole(checkRole);

        return checkingRole;
    }
    $scope.showPage = $scope.showIfAuthorized(checkRole);

authService.hasRole = function(role) {
        console.log('authService: begin role=' + role);
        console.log('Session.roles' + Session.roles);
        if (Session.roles != null) {
            document.cookie = "Session.roles="+Session.roles;
        }

        if (Session.roles == null) {
            Session.roles = authService.getCookie("Session.roles");
            console.log("Session.roles after refresh = " + Session.roles);
        }
        if (Session.roles === null && authService.getCookie("Session.roles") === null)
            return false;

        var indx = Session.roles.indexOf(role);
        console.log('hasRole: indx = ' + indx);
        if (indx >= 0)
            return true;
        return false;
    }

当我尝试运行时,我收到错误,“checkRole未定义”

2 个答案:

答案 0 :(得分:2)

您不应直接执行showIfAuthorized函数。代码应该像

$scope.showPage = $scope.showIfAuthorized;

或者您可以直接从ng-show中调用showIfAuthorized函数,如

ng-show = "showIfAuthorized('CRM Read')"

答案 1 :(得分:0)

将代码更改为

$scope.showPage = function(checkRole){
  //indirectly calling method
  $scope.showIfAuthorized(checkRole);
}

否则直接从UI中调用方法

ng-click = "showIfAuthorized('CRM Read')"

希望这对你有所帮助。